Hi,

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!


In reply to Good practice with $_ scope? by erwan

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.