AndyM
AndyM

Reputation: 622

perl hash pair value in string

Im trying to figure how to send the value in $opt{p} and a straight string to the subroutine rather than an array.

use Getopt::Std;
my $opt_string = 'hdp:j:';
getopts( "$opt_string", \%opt ) or usage();

usage() if $opt{h};
}   

sub usage()
{
        print STDERR << "EOF";
        This program grabs the problem print request and puts them in folder for investigation.
        usage: $0 [-d] [-p printer]  [-j job]   -h        : this (help) message
        -p printer: problem printer
        -j file   : problem print job id
        -d        : print debugging messages to stderr

        example: $0 -p PRINTERQ -j 76063 -d
EOF
        exit;

}

sub find_printer
{
        my $printer = $_[0] ;
        print "Looking for printer $printer .. \n";

}


find_printer( $opt{p} )  or  die "Unable to find printer";

Upvotes: 2

Views: 542

Answers (3)

ysth
ysth

Reputation: 98398

@_ isn't really an array (usually - it temporarily becomes real if you take a reference to it), it's just there to provide a syntax for accessing parameters consistent with other perl syntax.

Upvotes: 1

czubatka
czubatka

Reputation: 61

According to perlvar [ http://perldoc.perl.org/perlvar.html ]:

Within a subroutine the array @_ contains the parameters passed to that subroutine.

and perlsub [ http://perldoc.perl.org/perlsub.html ]:

Any arguments passed in show up in the array @_ . Therefore, if you called a function with two arguments, those would be stored in $[0] and $[1] . The array @_ is a local array, but its elements are aliases for the actual scalar parameters. In particular, if an element $[0] is updated, the corresponding argument is updated (or an error occurs if it is not updatable). If an argument is an array or hash element which did not exist when the function was called, that element is created only when (and if) it is modified or a reference to it is taken. (Some earlier versions of Perl created the element whether or not the element was assigned to.) Assigning to the whole array @ removes that aliasing, and does not update any arguments.

@_ definitely is an array :)

Upvotes: 1

Tudor Constantin
Tudor Constantin

Reputation: 26861

The subroutine always receives an array - even if that contains a single parameter

Upvotes: 3

Related Questions