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

So the ?_ variable is more or less the same as any other variable? What you just did seemed as though you were just renaming something, i.e. $sentence to ?_ Is that wrong and it's doing something more?

Replies are listed 'Best First'.
Re^3: The $_ Special Variable
by ikegami (Patriarch) on Jun 21, 2011 at 17:57 UTC

    So the $_ variable is more or less the same as any other variable?

    Yes, there's nothing inherently special about it*. It's simply the variable many ops use if no alternate is specified.

    * — Like other punctuation variables, it transcends packages. That's a bit special, but it's not all that relevant in practice.

Re^3: The $_ Special Variable
by wind (Priest) on Jun 21, 2011 at 17:58 UTC

    $_ 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.

      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;