in reply to scope of my $x in if statements

There's the utterly hideous use of do:

if (do {my $x = f(); $x and g($x)}) { ... }
but, please, just use ikegami's suggestion

Replies are listed 'Best First'.
Re^2: scope of my $x in if statements
by ikegami (Patriarch) on May 07, 2009 at 21:07 UTC

    Speaking of hideous, the functional approach written in Perl:

    if (my $x = x(f(), \&g)) { ... }
    having defined x() as
    sub x { my ($x, $g) = @_; $x && $g->($x) }
Re^2: scope of my $x in if statements
by shmem (Chancellor) on May 07, 2009 at 21:48 UTC

    not either, because the scope of $x is confined to the do block:

    use strict; use warnings; sub f{0} sub g{1} if (do {my $x = f(); $x and g($x)}) { print "cheerful: $x\n"; } __END__ Global symbol "$x" requires explicit package name at scope.pl line 6.
      if (my $x = do {my $x = f(); $x and g($x)}) { print "cheerful: $x\n"; }

        Yes, that works with subroutine return, and subs that modify their arguments.

        sub g { $_[0] = "ikegami++" } ... __END__ cheerful: ikegami++