Reputation: 1
How can i do something like that: I want return IP server from if statment, where i sign if to variable. It is possible?
#!/usr/bin/env perl
#
use warnings;
use strict;
my $variable1 = "10.12.1.1";
my $variable2 = "10.12.1.2";
my $string = $ARGV[0];
my $serveris=>(if ($string =~ m/^[abcdefghijklm]/) {
print " $variable1 \n"
} else {
print " $variable2 \n"
})
print $serveris
Upvotes: 0
Views: 1045
Reputation: 2320
The simplest option for your example code is to use the ternary operator:
my $serveris = $string =~ m/^[abcdefghijklm]/
? $variable1
: $variable2;
However, if things are more complicated, nested ternary operators can cause some confusion. To maintain the structure of your if/else
statements, use a do
block. do
returns the result of the last statement evaluated in the block as its value.
my $serveris = do {
if ($string =~ m/^[abcdefghijklm]/) {
$variable1;
} else {
$variable2;
}
};
Upvotes: 0
Reputation: 1655
You can make use of lambda functions.
#!/usr/bin/env perl
use warnings;
use strict;
my $variable1 = "10.12.1.1";
my $variable2 = "10.12.1.2";
my $string = $ARGV[0];
my $serveris = sub {
my ( $string ) = @_;
if ($string =~ m/^[abcdefghijklm]/) {
return " $variable1 \n"
} else {
return " $variable2 \n"
}
};
print $serveris->($string)
References: How to run an anonymous function in Perl?
Upvotes: 3
Reputation: 3013
Two ways to do that are to use the ternary operator ?:
, or move the assignment into the body of the if
:
use warnings;
use strict;
my $variable1 = "10.12.1.1";
my $variable2 = "10.12.1.2";
my $string = "x";
my $serveris =
$string =~ m/^[abcdefghijklm]/
? $variable1 : $variable2;
# -- OR --
my $serveris;
if ($string =~ m/^[abcdefghijklm]/) {
$serveris = $variable1;
} else {
$serveris = $variable2;
}
print " $serveris \n"
Upvotes: 4