in reply to Re: Unexpected value of $_ in a for loop.
in thread Unexpected value of $_ in a for loop.

(Firstly, thanks to the monks above for more efficient routines.)

The statement: push(@deck, splice(@_,$rand,1)); is what puzzles me (in my code).

After writing a sub:

my @arr = (5 .. 10); call_sub(@arr); sub call_sub { print "\n\n@_\n\n"; for (0 .. 4) { print "$_\t@_\n"; } print "\n\n"; }

I believe that $_ is a separate variable from @_ (and you can reference a scalar in @_ with $_[$sc]).

I had always assumed that $_ and @_ were connected, and that @_ referenced the elements in the for list as an array (which it doesn't).

It's a rather new discovery for me. Looking at how useful this is (rather than having to make temporary arrays in all your subroutines to carry parameters before going into a for loop), I see why it was done that way.

Dave.

Replies are listed 'Best First'.
Re: Unexpected value of $_ in a for loop.
by jonadab (Parson) on Jan 16, 2004 at 20:55 UTC
    I had always assumed that $_ and @_ were connected

    No. Well, yes, but not like that. They are connected in the sense that both of them have general punctuation-variable magic that exempts them from certain strictures and stuff. Also they can both be accessed using the typeglob *_ (as can %_ and &_ and the filehandle named _ if there is one). But that's all. Their values are not connected in any way.

    This is a general point that applies to all variables in Perl. Observe:

    no strict refs; use Data::Dumper; for $varname ('foo', 'bar', ':', '@%$!') { ${$varname} = "some scalar value"; @{$varname} = ('list', $$varname, \$$varname); %{$varname} = ( scalar => \$$varname, array => \@$varname ); print "-"x$=, $/; ::($varname); } sub :: { for (0) { print "For the variables named '$_[$_]':\n"; print Dumper(${$_[$_]}, \@{$_[$_]}, \%{$_[$_]}); } }

    Variables named '_' behave the same way, but it cannot be demonstrated with the above code because their values get overwritten in the middle of the demonstration because of the nature of their special magic (except %_, which has no special magic in Perl5).

    You can have a lot of fun writing obfuscations that abuse this, but there are also legitimate reasons to name an array and a scalar the same thing. One good example is if the sole purpose of the scalar is to serve as an index into the array (e.g., keeping track of the element your code is currently looking at). Especially if you have several such arrays each with its own current subscript scalar, naming them after one another can make it easier to keep track of what's what. Some would say that you should call them @foo and $fooindex or somesuch, but I tend to like to avoid superfluous verbosity in variable names.


    $;=sub{$/};@;=map{my($a,$b)=($_,$;);$;=sub{$a.$b->()}} split//,".rekcah lreP rehtona tsuJ";$\=$ ;->();print$/