test data test data - 27 days ago 5
Perl Question

How to use string concatenation inside if condition using perl?




I am using GetOptions to get the command line arguments if the command line arguments are not matched with the hash keys and values it should print invalid.I think to use string concatenation inside if condition.I tried the following query but am not getting the expected output?

GetOptions ("site=s" => \$site) or die("Error in command line arguments\n");
my %site_map = (bangalore => [ qw(rsdb_bangalore_1m rsdb_bangalore_current) ],
norwood => [ qw(rsdb_bangalore_1m rsdb_bangalore_current) ],
wilmington => [ qw(rsdb_bangalore_1m rsdb_bangalore_current) ],
limerick =>[qw(rsdb_bangalore_1m rsdb_bangalore_current)]);

for my $name (keys %site_map)
{
my $num_site = @{ $site_map{$name} };

if ($num_site == "rsdb_.$site_.1m || rsdb_.$site_.bangalore")
{
print "$num_site is success\n";
}
else
{
print "invalid\n";
}
}


Expected output:

rpasa-vd1-40: n1.pl -site "bangalore"(this should run at the terminal)
success(it should print the if condition after matching the site)

Answer

Concatenate outside of the quote characters or just use the join function:

'rsdb_' . $site . '_' . '1m'"

or

join('_', 'rsdb', $site, '1m')

In addition, you need to use string equality eq, not numeric equality ==.

I would rewrite your code like the following (it is a bit unclear what you want to from your question) :

#!/usr/bin/env perl

use strict;
use warnings;

use Getopt::Long;

my $site;
GetOptions("site=s" => \$site)
    or die "Error in command line arguments\n";
defined $site
    or die "usage: $0 site_name\n";

# TODO: Are these meant to have the same values?
my %site_map = (
    bangalore  => [ qw(rsdb_bangalore_1m rsdb_bangalore_current) ],
    norwood    => [ qw(rsdb_bangalore_1m rsdb_bangalore_current) ],
    wilmington => [ qw(rsdb_bangalore_1m rsdb_bangalore_current) ],
    limerick   => [ qw(rsdb_bangalore_1m rsdb_bangalore_current) ],
);

SITE_CHECK:
{
    for my $name (sort keys %site_map) {
        my @sites = @{ $site_map{$name} };
        for my $id ( 0 .. $#sites ) {
            my $num_site = join('_', 'rsdb', $site, '1m');
            if ($num_site eq $sites[$id]) {
                print "Found site '$num_site' in key '$name', position '$id'\n";
                last SITE_CHECK;
            }
        }
    }
    print "Invalid\n";
}

Output

perl foo.pl
usage: foo.pl site_name

perl foo.pl --site=foo
Invalid

perl foo.pl --site=bangalore
Found site 'rsdb_bangalore_1m' in key 'bangalore', position '0'