erwan has asked for the wisdom of the Perl Monks concerning the following question:
I just spent two days finding a bug in a complex program, which turned out to be related to $_... again (see http://www.perlmonks.org/?node_id=1154900). Here is a short version of the problem I had:
#!/usr/bin/perl use strict; use warnings; use bug::myitem; sub generate { my $list = shift; my @data; my $i=0; foreach my $f (@$list) { my $item = bug::myitem->new($i++, $f); push(@data, [$item, $i]); } return \@data; } my $data; if (scalar(@ARGV)>0) { $data = generate(\@ARGV); } else { die "syntax: <file1> <file2> ..." } print "Before:\n"; foreach my $item (@$data) { print "item->[0]=".$item->[0]." ; item->[1]=".$item->[1]."\n"; } my $dataStuff = map { $_->[0]->getContent() } @$data; print "After:\n"; foreach my $item (@$data) { print "item->[0]=".$item->[0]." ; item->[1]=".$item->[1]."\n"; }
and the class is this:
package bug::myitem; use strict; use warnings; sub new { my ($class, $id, $file) = @_; my $self; $self->{id} = $id; $self->{file} = $file; bless($self, $class); return $self; } sub getContent() { my $self = shift; my $fh; my $res; open($fh, "<",$self->{file}) or die "cannot open '".$self->{file}. +"'"; while (<$fh>) { chomp; $res .= $_."***"; } return $res; } 1;
I see now that I need to set $_ as local. I find it quite counter-intuitive to have to explicitly make local the default variable. My conclusion would be that I should always make it local whenever I use it, unless I intend to use it globally... and actually I can't think of any case where using it globally would be good programming practice.
What do you expert think? Thank you for your insight!
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Good practice with $_ scope?
by davies (Monsignor) on Jun 12, 2016 at 14:53 UTC | |
|
Re: Good practice with $_ scope?
by BrowserUk (Patriarch) on Jun 12, 2016 at 15:18 UTC | |
|
Re: Good practice with $_ scope?
by Anonymous Monk on Jun 12, 2016 at 14:27 UTC |