Requiring Lexical $_ / Obliterating Global $_?

P

Peter J. Holzer

But they're different scopes: "my" is lexical scopes but the implicit
declaration is dynamic scope.

1) I know.

2) Starting with 5.10: Not necessarily:

#!/usr/local/bin/perl5.10.0
use warnings;
use strict;

sub foo {
$_ = 'foo';
}

sub bar {
my $_ = 'bar';
for (1, 2, 3) {
print "$_\n";
foo();
print "$_\n";
}
print "$_\n";
}

bar();

(So adding "my $_" to the start of each file, as somebody in this
thread suggested, does indeed help against "weird" bugs)

Dynamic Scope Considered Harmful.

If each modification of $_ is surrounded with an (explicit or implicit)
local $_ with the smallest possible scope, there is little practical
difference.

The problematical constructs (i.e. those where you have to remember to
add a local $_) are "while (<>)" and direct assignment. Foreach, grep,
and map already add a scope by themselves. It should not be necessary
to make them more verbose.

hp
 
D

Dr.Ruud

Tim McDaniel schreef:
I've never seen
for ($some_scalar) {...}
While I've not read much Perl code written by others, I've not seen it
in examples either. ... though when looking up something else in
"man perlsyn", I see it's used there.

It's also not intuitive to me. I'm used to foreach iterating over a
list. My first thought was "you're guaranteed that there's no list.
Why bother with a 'loop' that you know will run only once?"

What can be wrong with short lists?

The other way around happens to, people writing

print $string
. "\n"
;

where they could write

print $string,
"\n",
;

(the above need not be identical, for example when the stringification
of $string is overloaded)
 
B

Ben Morrow

Quoth "Dr.Ruud said:
The other way around happens to, people writing

print $string
. "\n"
;

where they could write

print $string,
"\n",
;

(the above need not be identical, for example when the stringification
of $string is overloaded)

No, print still stringifies its arguments. However, $, makes them
different.

Ben
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,579
Members
45,053
Latest member
BrodieSola

Latest Threads

Top