Beefy Boxes and Bandwidth Generously Provided by pair Networks
Don't ask to ask, just ask
 
PerlMonks  

Re: On patterns and more

by ELISHEVA (Prior)
on Mar 06, 2011 at 12:57 UTC ( #891677=note: print w/ replies, xml ) Need Help??


in reply to On patterns and more

$_ is a variable that is set to whatever Perl thinks you are most likely to want to use as a default command/subroutine argument. Many Perl commands will automatically use whatever value is assigned to $_ so you don't have to do so much typing:

defined #same as defined($_) print #same as print STDOUT $_ /\sjackson$/ #same as $_ =~ /\sjackson$/

The actual value assigned to $_ depends on the context because what you are "most likely to want to use as an argument" usually depends on what you are doing in your code at that moment.

In a for loop $_ is the current array element.

When using grep or map it is also the current array element:

@only_defined = grep { defined($_) } @somearray; %hash_defined = map { $_ => 1 } @only_defined; #and since $_ is the default argument, you can also write @only_defined = grep { defined } @somearray; @only_begins_with_a = grep { /^a/ } @somearray;

If you are reading from a file using the <> operator, it is the most recently read line, e.g.

while (<STDIN>) { chomp # same as chomp $_ if (/^#/) {....} # same as if ($_ =~ /^#/) { ....} }

You don't have to use $_ for loops. In fact, for production code, it is a good idea not to because every so often something you are doing inside the for loop might unexpectedly reset $_ (it shouldn't but you don't always have control over other people's code and how they use things like $_. The inside of loops often makes calls to other people's code). For example, your loop above could also have been written:

#Note this code still won't work - see sherm's explanation below. foreach my $name (@myNames) { if($name =~ "jackson") print $name . "\n"; #sic - should be { print $name . "\n" } }

The same caution about $_ also applies to $_ when reading from an input stream or any other use of $_. If you are doing something complicated, it is best to assign $_ to a variable with a name you control and to use that variable instead of $_. Thus a better way to write the code reading from STDIN above would be

while (my $line = <STDIN>) { chomp $line; if ($line =~ /^#/) {....} }

Update: added comment about non-working code and referenced sherm's explanation below.


Comment on Re: On patterns and more
Select or Download Code

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others imbibing at the Monastery: (15)
As of 2014-09-30 19:34 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    How do you remember the number of days in each month?











    Results (381 votes), past polls