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.
You can use square brackets to create a reference to an array:
pass_in( $str, [qw(A B C D E)]);
perldoc perlref
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 ) );
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With