Beefy Boxes and Bandwidth Generously Provided by pair Networks
P is for Practical

Re: The $_ Special Variable

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

in reply to The $_ Special Variable

In that instance, $_ could be anything. But you can assign directly to $_ to let m// use it as default instead.
$_= "Best winkles in Sunderland"; if (/under/) { print "We're talking about rugby\n"; }
The more common use of $_ is when it's the default iterator in a for loop, or in a while loop when reading from a file.
# Instead of having for my $iter, for uses $_ as the iterator below: for ("Up and under", "Best winkles in Sunderland") { if (/under/) { print "We're talking about rugby\n"; } }

Replies are listed 'Best First'.
Re^2: The $_ Special Variable
by chuloon (Initiate) on Jun 21, 2011 at 17:52 UTC
    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?

      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.

      $_ 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; } }

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://910780]
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others making s'mores by the fire in the courtyard of the Monastery: (4)
As of 2018-02-24 11:05 GMT
Find Nodes?
    Voting Booth?
    When it is dark outside I am happiest to see ...

    Results (310 votes). Check out past polls.