in reply to global $_ behavior

$_ is not block scoped; it's just an ordinary global variable that happens to be the default target for various operations. foreach just aliases the loop variable ($_ by default) to each element in turn.

Dave.

Replies are listed 'Best First'.
Re^2: global $_ behavior
by jonix (Friar) on Dec 02, 2005 at 16:06 UTC
    $_ is not block scoped; it's just an ordinary global variable that happens to be the default target for various operations.
    Thank you for this clear statement. I have been trapped by the globalness of $_ myself some times - it just feels quite natural for the beginner to assume that implicit assignment to $_ should also scope $_ implicitly to the assigning block.
    Well, it does not unless you make it explicitly local.
    I guess there are many good reasons for this :)
      There aren't really many good reasons for $_ to be global, and the main reason it's that way is simply that when Perl started out, all variables were globals. So Perl 6 is changing $_ to be implicitly lexically scoped to each sub. For those rare occasions where a sub wants to look at the $_ of its caller, it can use CALLER::<$_> to do that.