Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl: the Markov chain saw
 
PerlMonks  

Re: The $_ Special Variable

by wind (Priest)
on Jun 21, 2011 at 17:46 UTC ( [id://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?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others chanting in the Monastery: (5)
As of 2024-03-29 05:35 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found