in reply to Re: Re: $_ haters anonymou
in thread $_ haters anonymou

<MODE TYPE="SILLY/STUPID">Why don't we just drop $_ and use things like $extremly_really_long_variable_name as our commonly used loop variables. This could allow programmers to write fully documented code without comments ie $variable_to_store_data_from_function_call_named_foo_and_mutate_it_with_many_operators. Think how easy it would be to write that type of code and all the time that could be saved not using punctuation like hmmm..$_, and making everything much clearer in the process. That way we could also allow all variables to be fully global because name collision should be quite difficult (hell you'll need reams of paper just to remember them, why not use a few common ones with a few character changed, such as adding _ on the end).</MODE>

Or maybe we need an automatic local $_; at the beginning of each sub and in each package (which would solve some/all of what you were saying).
You could put that in all your subs where you use $_ which can be called by other things.
Then when calling other people's code enclose it in its one block:

#.... my $var = Package::sub; #.... # changed to #.... my $var; { local $_; $var = Package::sub; } #....
This is the only (?) way to make absolutly sure that other code won't accidently wipe $_.
There are also other cases where we need to keep the closest eye on what is happening with $_ (for both our brains and the compiler).
$_ = 'foo'; while (<>) for (grep {/$_/} @foo) { for (map {ord($_)} split //,$_) { while (--$h{$_}>10) {print $_} } s/a/b/g; print 'middle' . $_; } print 'outer' . $_; } print $_;
There are 4 seperate $_'s there and while they mostly don't collide you need to keep an eye on where they are all going. This could be even worse if this kind of code is mixed in with lots of other statements.
So $_ is just one more thing perl programmers have to keep a close eye on (but still keep on using).

Replies are listed 'Best First'.
Re: Re: Re: Re: $_ haters anonymou
by tilly (Archbishop) on Dec 11, 2000 at 16:04 UTC
    Well why not have $_ be automatically lexical?

    Works perfectly well. But breaks backwards compatibility. But I think it will happen in Perl 6.

      Enh, but then it's impossible to define subroutines that work like built-ins such as chomp.

      I do that not infrequently.

      However, I wouldn't mind having to go through hoops to get there. Perhaps a subroutine attribute would have to be set to allow you access to $_.

      sub mychomp : getunderscore { s[${/}\z][]; }

      That way, no one could clobber $_ without intending to. And we could also add a pragma to disallow code outside of your file (or perhaps package) from clobbering $_ even if it wanted to.

      -dlc