in reply to Re^2: why not listed foreach and if?
in thread why not listed foreach and if?

why the restriction?

It's just that perl's parsing does not handle these types of constructs.
It interprets:
foreach @a if $a as foreach(@a if $a)
foreach takes a list as its argument, and I guess perl just doesn't see (@a if $a) as being a valid list.

You know what you mean, and I know what you mean, but perl doesn't.
I don't know exactly why perl doesn't understand these constructs ... but I suspect there are good reasons.

Cheers,
Rob

Replies are listed 'Best First'.
Re^4: why not listed foreach and if?
by hv (Prior) on Jun 18, 2024 at 00:30 UTC

    I'm also not sure why perl doesn't understand them. I suspect they must lead to parsing ambiguities - that usually seems to be the reason for such restrictions.

    In any case, Perl does not have a history of disallowing things on the grounds of "readability" (that seems much more Python's style). What a person finds readable is very much determined by what they are used to, there really is no single perfect style.

    Around 25 years ago I was working at Elsevier in Amsterdam, and once had a very heated discussion with the project lead when in code review he wanted to turn my mix of loops and map/grep pipelines (carefully curated so that no single construct was overly complex) into a single much more complex map/grep pipeline that to me seemed totally illegible. My line manager eventually explained that the lead had a functional programming background, and that I should look at the proposed change in that light. It took me a while, but eventually I got my head around it, and I'm now much more comfortable with that style (and find it perfectly legible when done right).

      Perl does not have a history of disallowing things on the grounds of "readability"

      Yeah, so it's odd that it's done here. But that was the reason given by Larry Wall (as I remember things).

      I suspect they must lead to parsing ambiguities

      Well yeah. Is X MODA Y MODB Z equiv to ( X MODA Y ) MODB Z or X MODA ( Y MODB Z )? But that the same applies to every binary operator. These ambiguities are resolved using associativity and precedence.

Re^4: why not listed foreach and if?
by rsFalse (Chaplain) on Feb 01, 2025 at 12:13 UTC
    Hi,
    How you know that perl interprets as foreach(@a if $A) but not (foreach @a) if $A?

    I see any of constructs if/for/while can be written inside of parentheses, e.g. a simple ($A if $A) is a syntax error.

    'and' and 'if' internally, as I understand, branch equivalently, only the direction differs. And the result of 'if' becomes not an expression, when the result of 'and' becomes an expression.