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

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]
[shmem]: msh210: you can save the perlbug text in a file and send that via your mail agent of choice
[msh210]: hm, okay, I'll try, thanks
[shmem]: ...not as an attachment, it's probably better to c&p that into the mail body

How do I use this? | Other CB clients
Other Users?
Others browsing the Monastery: (12)
As of 2017-04-24 12:53 GMT
Find Nodes?
    Voting Booth?
    I'm a fool:

    Results (439 votes). Check out past polls.