in reply to Help with perl syntax

"If" and "unless" are both logical operators, governed by the same syntax. In fact, they are opposites, as "if" tests for something that is true, while "unless" tests for something that isn't true. Nevertheless, you can't combine them in Perl with the same sort of flexibility that you can in English... you can do one, or the other, but you can't combine them to create some sort of weird hybrid expression like you can in English.

For example,

unless (/^#!/) {next READ if (/^\s*#/)};
can be rewritten like this:
unless (/^#!/) { if (/^\s*#/) { next READ; } }
Notice how there's really two logical operations going on, completely separate from one another. First, the "unless", with its code-block, and then (within the "unless" code block) an "if" statement with its own code-block. Makes perfect sense, and the Perl interpreter has no problems.

However, the next example:

if (/^\s*#/) { next READ } unless (/^#!/);
would be rewritten as:
if (/^\s*#/) { next READ } unless (/^#!/);
which doesn't work at all. Where's the code-block for the "unless" statement? Perl doesn't see one, and so throws up its hands because it doesn't know what to do.

If you confuse yourself with the reverse notation, just try to rewrite it in the "proper" way and you'll see very clearly what will and won't work.

Gary Blackburn
Trained Killer

Replies are listed 'Best First'.
RE: Re: Help with perl syntax
by merlyn (Sage) on Oct 29, 2000 at 05:42 UTC
    In BASIC-PLUS, which is where Larry stole the IF/WHILE/UNTIL/UNLESS suffix forms, you can nest them, however. So, this would be legal:
    print $_ if $_ % 2 while <INPUT>; # not legal in Perl, but in pseudo-B +ASIC-PLUS
    However, in Perl you're forced to write that in two pieces somehow:
    $_ % 2 and print $_ while <INPUT>;
    or
    while (<INPUT>) { print $_ if $_ % 2 }
    I believe Larry thought the nested stacked suffix operations were hard to parse, and I agree with him.

    -- Randal L. Schwartz, Perl hacker