开发者

Is there a way to use 'else' as a modifier in Perl 'if' constructs (like for 'if')?

开发者 https://www.devze.com 2023-01-23 23:33 出处:网络
I have seen if(cond) {} elsif(cond2) {} else {} statement if(cond) unless(cond) {} But is there a statement if(cond)

I have seen

if(cond) {} elsif(cond2) {} else {}
statement if(cond)
unless(cond) {}

But is there a

statement if(cond)
st开发者_开发技巧atement2 elsif(cond)
statement3 else

and

if(cond) {}
elsun(cond){} # un meaning else unless


No, see perldoc perlsyn.


No, there is only the first.

Trailing if modifier is probably more accurately shown as:

statement if cond

That is, there's no need for parentheses around the condition (since they're not needed for disambiguation).


Pretty much:

print "foo\n" if ($foo eq $bar);

is a shortcut for

if ($foo eq $bar) {
    print "foo\n";
}

And, I rarely use the previous because in the second example, the if statement is more obvious than in the first example. The only time I've used the postfixed if is something like this:

next if ($line =~ /^\s*$/);

That's usually short enough to catch.

You might want to try:

use Switch;
switch ($val) {
    case 1          { print "number 1" }
    case "a"        { print "string a" }
    case [1..10,42] { print "number in list" }
    case (\@array)  { print "number in list" }
    case /\w+/      { print "pattern" }
    case qr/\w+/    { print "pattern" }
    case (\%hash)   { print "entry in hash" }
    case (\&sub)    { print "arg to subroutine" }
    else            { print "previous case not true" }
}

which is what I think you really are looking for. BTW, I've had problems with Switch and it doesn't work with older versions of Perl (pre Perl 5.8).

0

精彩评论

暂无评论...
验证码 换一张
取 消