azaria has asked for the wisdom of the Perl Monks concerning the following question:

I want to map an array into str1, str2, str3 accordignly, how can I do it smoothly - my (@vars) = @_; @new = map {CODE} @vars; what should be the code? Azaria

Replies are listed 'Best First'.
Re: Mapping Array
by pg (Canon) on Oct 29, 2005 at 22:54 UTC
    use strict; use warnings; my @vars = (1,2,3); my ($str1, $str2, $str3) = map {"string" . $_} @vars; print $str1, "\n"; print $str2, "\n"; print $str3, "\n";

    Also you don't need @vars, just:

    my ($str1, $str2, $str3) = map {"string" . $_} @_;
Re: Mapping Array
by graff (Chancellor) on Oct 30, 2005 at 02:12 UTC
    What should be the code? That depends on what you want to do with the values in your original array. If all you want is to move them as-is (unmodified) into separate scalar variables, you don't need map at all:
    sub show_scalars { my ( $str1, $str2, $str3 ) = @_; print "Last was $str3, preceded by $str2, and $str1 was first\n"; } my @array = qw/one two three/; show_scalars( @array );
    But as pg showed in the first reply, map is good for when you want to derive a set of modified values from an array or list, by applying a chunk of code to each element.