Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perl subroutine arguments like a hash

How can I create a subroutine that can parse arguments like this:

&mySub(arg1 => 'value1', arg2 => 'value2' ...);

sub mySub() {
    # what do I need to do here to parse these arguments?
    # no arguments are required
}
like image 375
netdjw Avatar asked Apr 27 '15 15:04

netdjw


People also ask

How do you pass arguments in Perl subroutine?

Passing Arguments to a Subroutine You can pass various arguments to a subroutine like you do in any other programming language and they can be acessed inside the function using the special array @_. Thus the first argument to the function is in $_[0], the second is in $_[1], and so on.

What is the difference between shift and @_ used in passing arguments to subroutine?

There is a functional difference ... shift modifies @_ while assignment does not.

What is subroutine in Perl explain with suitable example?

A Perl function or subroutine is a group of statements that together perform a specific task. In every programming language user want to reuse the code. So the user puts the section of code in function or subroutine so that there will be no need to write code again and again.


1 Answers

Simply assign the input array to a hash:

sub my_sub {
    my %args = @_;
    # Work with the %args hash, e.g.
    print "arg1: ", $args{arg1};
}

If you want to provide default values, you can use:

sub my_sub {
    my %args = ( 'arg1' => 'default arg1',
                 'arg2' => 'default arg2',
                 @_ );
    # Work with the (possibly default) values in %args
}
like image 87
RobEarl Avatar answered Nov 13 '22 18:11

RobEarl