Beefy Boxes and Bandwidth Generously Provided by pair Networks
Do you know where your variables are?

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 ?

Comment on Converting Array elements into hash key - value pairs
Select or Download Code
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 the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others making s'mores by the fire in the courtyard of the Monastery: (4)
As of 2016-02-13 01:22 GMT
Find Nodes?
    Voting Booth?

    How many photographs, souvenirs, artworks, trophies or other decorative objects are displayed in your home?

    Results (415 votes), past polls