sub get_list {
return ("one", "two");
}
sub get_array {
my @a = ("one", "two");
# need to convert @a to list
return @a;
}
my $two = get_list(); # desired, assigns last item in list to scalar
my $count = get_array(); # evaluates array in scalar context, returning a count
In the get_array() method, I already have an array created, but I want to return it as a list so that it assigns according to list rules and not array rules. The array of course would normally be built in a more complex way (not directly from a list).
I have tried using map in hopes that it would return me a list of values, but this gives the same results. Same with split/join.
return map { $_ } @a;
return split /,/, join(",", @a);
How can I convert the array into a list of values?
Functions can use wantarray to determine the context they're in and return something accordingly:
sub get_array {
my @a = ("one", "two");
return wantarray ? @a : $a[-1];
}
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