Beefy Boxes and Bandwidth Generously Provided by pair Networks
more useful options

Re^3: The $_ Special Variable

by wind (Priest)
on Jun 21, 2011 at 17:58 UTC ( #910783=note: print w/ replies, xml ) Need Help??

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.

Comment on Re^3: The $_ Special Variable
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;
        Oh, duh. Thanks. I can't believe I overlooked that.
        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

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://910783]
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others exploiting the Monastery: (10)
As of 2015-03-29 19:48 GMT
Find Nodes?
    Voting Booth?

    When putting a smiley right before a closing parenthesis, do you:

    Results (632 votes), past polls