Beefy Boxes and Bandwidth Generously Provided by pair Networks
Just another Perl shrine
 
PerlMonks  

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.
Or,
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);
-----OUTPUT------
$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
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?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://826489]
Approved by ikegami
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others drinking their drinks and smoking their pipes about the Monastery: (7)
As of 2014-07-24 03:21 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    My favorite superfluous repetitious redundant duplicative phrase is:









    Results (156 votes), past polls