Problem with Perl

Started by Ningey, January 14, 2012, 03:02:35 PM

Previous topic - Next topic

0 Members and 1 Guest are viewing this topic.

Ningey

Kaltxì!
In order to implement a name generator I need to set up a hash that has the following structure:
%hash = ( 'a' => [( 1, [( 'a1' => 1, 'b1' => 2, 'c1' => 3, ... )])],
               'b' => [( 1, [( 'a2' => 4, 'b2' => 3, 'c2' => 5, ... )])],
               ... );


So far, so good, I can extract the keys from the top level of said hash, but when I attempt to extract the keys from the other hash I had to nest, I'm out of luck. I might be able to extract the nested hash, but obtaining its keys fails.
Any solutions?

However, the prerequisite is that no auxiliary variables are used and the whole thing happens on a single line.


"Sawtute ke tsun nivume - fo ke kerame!"
-- Neytiri te Tskaha Mo'at'ite

"There are two things that are infinite: Human stupidity and the universe. However, I'm not yet sure about the universe."
-- Albert Einstein

"He who gives up freedom for security deserves neither and loses both."
-- Benjamin Franklin

wm.annis

Quote from: Ningey on January 14, 2012, 03:02:35 PMHowever, the prerequisite is that no auxiliary variables are used and the whole thing happens on a single line.

Eh.  Perl.  I used to be a hardcore perl user then switched to Python precisely because of problems with nested complex structures like this.  Regardless...

When you stick another hash or an array inside another hash or array, what you really have is a reference to a hash or array.  So, you have to use a slightly different notation to get things out.


#!/usr/bin/env perl

use Data::Dumper;

%hash = ( 'a' => [( 1, [( 'a1' => 1, 'b1' => 2, 'c1' => 3)])],
          'b' => [( 1, [( 'a2' => 4, 'b2' => 3, 'c2' => 5)])]);


print %hash->{'a'}, "\n";
print %hash->{'a'}[1], "\n";
print %hash->{'a'}[1][1], "\n;"

print Dumper(%hash);


I always used the library Data::Dumper to disentangle the mess I was creating with embedded structures in Perl.

wm.annis

I should add — you might find these helpful: http://www.perl.com/doc/FMTEYEWTK/pdsc/ and http://docstore.mik.ua/orelly/perl/prog3/ch09_01.htm

Dealing with these is a notorious vexation in perl.

Ningey

Irayo nìtxan.

I just noticed where things have gone awry in the first place, and now I managed to make the thing work as it should without having to resort on any helpers (I just had to put the array in angle brackets and the nested hash in curly brackets).

Now with the correct declaration the thing works just fine.

But nevertheless your help is much appreciated.


"Sawtute ke tsun nivume - fo ke kerame!"
-- Neytiri te Tskaha Mo'at'ite

"There are two things that are infinite: Human stupidity and the universe. However, I'm not yet sure about the universe."
-- Albert Einstein

"He who gives up freedom for security deserves neither and loses both."
-- Benjamin Franklin