nite_man has asked for the wisdom of the Perl Monks concerning the following question:

Hi brothers,
All of us know than $_ is default variable for some perl statments in one of which is  for.
My question is: if we use a following:
for(1..10) { for(20..30) { print $_; } }
it's possible to get a value of $_ from first loop or I have to use some variable intead of $_?
--------> SV* sv_bless(SV* sv, HV* stash);

Replies are listed 'Best First'.
Re: Loop 'for' and '$_'.
by dragonchild (Archbishop) on Mar 31, 2003 at 16:55 UTC
    Try the following and see for yourself. :-)
    #!/usr/bin/perl -w use strict; for (1 .. 10) { print $_, $/; for (11 .. 20) { print "\t$_", $/; } print $_, $/; }
    You have to use another variable, just like $my_other_var or anything else.

    ------
    We are the carpenters and bricklayers of the Information Age.

    Don't go borrowing trouble. For programmers, this means Worry only about what you need to implement.

    Please remember that I'm crufty and crochety. All opinions are purely mine and all code is untested, unless otherwise specified.

Re: Loop 'for' and '$_'.
by Lhamo Latso (Scribe) on Mar 31, 2003 at 17:21 UTC

    I would be careful about using nested $_ variables in nested "for" loops. I encountered a bug in Perl 5.8.0, to be fixed in 5.8.1, that is detailed in Unbalanced string table refcount.

    The better, and less buggy, approach is to use:

    for my $loop_outer (... for my $loop_innermost (...
Re: Loop 'for' and '$_'.
by roundboy (Sexton) on Mar 31, 2003 at 17:33 UTC
    If you wrote:
    for my $x (1..10) { for my $x (11..20) { print $x; } }
    you wouldn't expect to be able to access the outer $x, would you? Well, $_ is just another variable, except that you don't have to name it.
Re: Loop 'for' and '$_'.
by Coruscate (Sexton) on Apr 01, 2003 at 09:01 UTC

    There is one little exception. Taking the snippet from roundboy's and modifying it slightly, we get this code which allows you to have 2 same-named, but 2 differently-scoped variables and differenciate between them in a nested loop. I tried manipulating this to work with $_, but it just won't happen. :) Note that you have to put in more work to use this than simply using 2 differently named variables. And this is ugly lol.

    for our $x (1..2) { for my $x (3..4) { print "$::x, $x\n"; } }


    If the above content is missing any vital points or you feel that any of the information is misleading, incorrect or irrelevant, please feel free to downvote the post. At the same time, please reply to this node or /msg me to inform me as to what is wrong with the post, so that I may update the node to the best of my ability.