http://www.perlmonks.org?node_id=910783


in reply to Re^2: The $_ Special Variable
in thread The $_ Special Variable

$_ is just a special global variable as defined in perlvar.

It is used as the default input for a lot of builtin functions when nothing else is defined. But yes, it can be thought of as just any other variable, just one that is declared automatically by perl to enable you to write tighter code when you want to.

Replies are listed 'Best First'.
Re^4: The $_ Special Variable
by chuloon (Initiate) on Jun 21, 2011 at 18:03 UTC
    Could you tell me why this code doesn't work then? I thought I had the right syntax.
    $file = 'electricity.txt'; open(INFO, $file); @lines = <INFO>; close(INFO); $counter = 1; foreach $line (@lines) { if ($line =~ /$ARGV[0]/) { print "$counter "; $_ = $line; s/$ARGV[0]/($ARGV[0])/g; print $line; $counter++; } else { print $line; } }

      If you're talking about this section of the code:

      $_ = $line; s/$ARGV[0]/($ARGV[0])/g; print $line;

      It's because $line and $_ are two different variables. your s/// is changing $_ there, so that's what you'd need to print out if you wanted to see the change.

      Note: I'd change a lot of things about your script, but starting with adding use strict and use warnings to the top. Here is a cleaned up version with strictures in place:

      use strict; use warnings; my $string = shift; my $file = 'electricity.txt'; open my $fh, '<', $file or die $! my $counter = 0; while (<$fh>) { if (s/\Q$string\E/($string)/g) { $counter++; print "$counter "; } print; } close $fh;
        What do the strict and warnings commands do? And what is the purpose of my before the objects? What does it do? Also, what is the purpose of my $string = shift;? I don't understand the if (s/\Q$string\E/($string)/g) { conditional either. Thank you for all of your help
        Oh, duh. Thanks. I can't believe I overlooked that.