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$/
In reply to Re: Unexpected value of $_ in a for loop.
by jonadab
in thread Unexpected value of $_ in a for loop.
by David Caughell
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |