Item 8: Know the other default arguments: _ , ARGV , STDIN .

Item 8: Know the other default arguments: @_ , @ARGV , STDIN .

$_ is not the one and only default argument in Perl. There are several others.

@_ as a default

Inside a subroutine, shift uses @_ as a default argument:

 sub foo {     my $x = shift; 

$x gets the first argument.

One interesting quirk in Perl syntax shows up when you try to shift an array argument passed by reference:


Pass ref to @bletch to sub &bar .

 sub bar {    my @a = @{shift}; 

OOPS! This is the variable @shift .

You have to put something else inside the braces to let Perl know that the identifier isn't a variable name :

 my @a = @{shift()}; 

My preferred form.

 my @a = @{+shift}; 

Works, but looks weird to me.

@ARGV as a default

On the other hand, outside a subroutine, shift uses @ARGV as a default:

 while ($_ = shift) {    if (/^-(.*)/) {      process_option();    } else {      process_file($_);    }  } 

Shifting @ARGV by default.

Process opt if starts with - .

Otherwise it's a file.

The shift operator always uses the main @_ or @ARGV even if your default package is something other than main .

STDIN as a default

Unlike the rest of the file test operators, which use $_ as a default, the -t operator uses the filehandle STDIN as a default. -t tests a filehandle in the manner of the Unix isatty() function to determine whether the filehandle is interactive, that is, whether input is coming from a human typing at a keyboard:

 print "You're alive!" if -t STDIN;  print "You're alive!" if -t; 

Are we talking to a human?

Same thing.

Use the -t operator to help modify the behavior of a program, depending on whether it is running interactively. For example, you could use -t in a CGI script to start it up in a special debugging mode if the script is being run from the command line.

Effective Perl Programming. Writing Better Programs with Perl
Effective Perl Programming: Writing Better Programs with Perl
ISBN: 0201419750
EAN: 2147483647
Year: 1996
Pages: 116

Similar book on Amazon © 2008-2017.
If you may any questions please contact us: