perlpal has asked for the wisdom of the Perl Monks concerning the following question:
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 :
-----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 (Patriarch) on Mar 03, 2010 at 18:32 UTC |