Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass string and temporary array into sub in 1 line?

Tags:

perl

I made a subroutine that I want to pass a string and an array into:

sub pass_in {
    my ($str, $array) = @_;
    for my $e (@$array) {
        print "I see str $str and list elem: $e\n";  
    }
    return 0;
}

my @temp_arr =  qw(A B C D E);
my $str = "hello";
pass_in( $str, \@temp_arr );

This works fine, but I don't want to have to create a temp_arr. Is it possible to do?

Doesn't work:

pass_in( $str, qw(A B C D E));

Also doesn't work:

pass_in( $str, \qw(A B C D E));

I don't want to create a temporary variable.

like image 533
B Eff Avatar asked May 12 '16 13:05

B Eff


2 Answers

You can use square brackets to create a reference to an array:

pass_in( $str, [qw(A B C D E)]);

perldoc perlref

like image 186
toolic Avatar answered Nov 13 '22 09:11

toolic


In order to pass an in array, you have must an array to pass!

qw() does not create an array. It just puts a bunch of scalars on the stack. That for which you are looking is [ ]. It conveniently creates an array, initializes the array using the expression within, and returns a reference to the array.

pass_in( $str, [qw( A B C D E )] );

Alternatively, you could rewrite your subroutine to accept a list of values.

sub pass_in {
    my $str = shift;
    for my $e (@_) {
        print "I see str $str and list elem: $e\n";  
    }

    return 0;
}

pass_in( "hello", qw( A B C D E ) );
like image 20
ikegami Avatar answered Nov 13 '22 07:11

ikegami