Here is a recursive solution written more for clarity than conciseness. It'll give a basic idea anyway:
#!/user/bin/env perl
use strict;
use warnings;
use Data::Dumper;
my @array = qw(a b c d e f g h i 123);
my $recurse_level = 0;
sub to_hash {
my $hash_ref = shift;
my @array = @_;
my $array_count = @array;
die "Need at least 2 elements in original array" if (0 == $recurse_l
+evel && 2 > $array_count);
my $index;
if (2 < $array_count) {
$index = shift @array;
$recurse_level++;
$hash_ref->{$index} = to_hash({},@array);
}
else {
$index = shift @array;
$hash_ref->{$index} = shift @array;
}
return $hash_ref;
}
my $hash_ref = to_hash({},@array);
print Dumper($hash_ref);
Output:
$VAR1 = {
'a' => {
'b' => {
'c' => {
'd' => {
'e' => {
'f' => {
'g' =>
+ {
+ 'h' => {
+ 'i' => '123'
+ }
+ }
}
}
}
}
}
}
};
Update
Triple bonus points to whomever modifies this code to allow for more complex data structures to be created by feeding it multiple arrays - the current code only returns a hash for /the/ array passed to it. I know why, but I can figure out right now how to fix it...if I figure it out, I'll update the code.
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.