Beefy Boxes and Bandwidth Generously Provided by pair Networks
good chemistry is complicated,
and a little bit messy -LW

Converting Array elements into hash key - value pairs

by perlpal (Scribe)
on Mar 03, 2010 at 18:24 UTC ( #826489=perlquestion: print w/replies, xml ) Need Help??
perlpal has asked for the wisdom of the Perl Monks concerning the following question:

Hi Perl Monks,

The requirement is to convert the elements of an array into corresponding key-value pairs.

The logic is either of the following :
The even-indexed elements are keys to the immediate succeeding odd-indexed elements which are corresponding values.
The elements in uppercase are keys with the next element as its corresponding value if it is not an uppercase element.

Using the second logic, i have the following code and output :

my $help_hash; my $key; my @help_arr = qw(NAME larry SURNAME wall CODE perl); foreach my $element(@help_arr) { if ($element =~ /^[A-Z]{3,}$/){ $key = $element; }else{ $help_hash->{$key} = $element; } } print Dumper ($help_hash);
$VAR1 = { 'SURNAME' => 'wall', 'NAME' => 'larry', 'CODE' => 'perl' };

Is there a more efficient way to do the same ?

Replies are listed 'Best First'.
Re: Converting Array elements into hash key - value pairs
by ikegami (Pope) on Mar 03, 2010 at 18:32 UTC
    You can assign a key-val list to a hash.
    my %help_hash = @help_arr; print Dumper \%help_hash;

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://826489]
Approved by ikegami
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others studying the Monastery: (4)
As of 2017-07-22 02:56 GMT
Find Nodes?
    Voting Booth?
    I came, I saw, I ...

    Results (336 votes). Check out past polls.