Friday, June 24, 2011

$_(default) in perl

$_ is the default argument
It is the default argument for many operators and also some control structures.
$_ is a normal scalar variable and it can be used as a normal scalar variable,you can change it.print it and use it.
Some of the common usuages of $_ and how the default operator is automatically interpreted in perl :

print $_;
print;                        Same result

print "found it" if  $_ =~ /Rosebud/;
print  "found  it " if  /Rosebud/;               Same result

foreach $_(@list) { &do_something($_) };e
foreach (@list){  &do_something($_) };       Same result

while (defined($_ = <STDIN>)){ print $_; }
while(<STDIN>){ print ; }                                 Same result

$_ always belongs to the main package.
Even if you define $_ in some other package it will default always to $main::$_

package hello;
package main:
print $_;       #  it prints hai
Here hai as print $_;  is same as --->  print $main::$_;

You can even use $hello::$_ and assign it some value.print it.But this is not same as $_ and it has no special property.

No comments:

Post a Comment