in reply to enabling OO and non-OO access to the same module using a hash reference

Hi Moron,

Here's an interesting experiment (well, I think it's interesting, as I wasn't quite sure how it would turn out):

#!/usr/bin/perl -w use strict; use warnings; use Data::Dumper; my %hash = ( 'a' => 'b', 'c' => 'd', 'e' => [ 'F', 'G', 'H' ], 'i' => { 'J' => 'K', 'L' => 'M', }, ); as_hash(%hash); as_array(%hash); sub as_hash { my (%hash) = @_; printf "Dump of hash as a hash => %s\n", Dumper(\%hash); my $hash_i_J = $hash{'i'}{'J'}; printf "hash{i}{J} = '%s'\n", $hash_i_J; } sub as_array { my (@array) = @_; print "\nEach element of \@array:\n"; map { print "- $_\n" } @array; printf "\nDump of hash as an array => %s\n", Dumper(\@array); as_hash(@array); }

Which outputs:

Dump of hash as a hash => $VAR1 = { 'e' => [ 'F', 'G', 'H' ], 'c' => 'd', 'a' => 'b', 'i' => { 'J' => 'K', 'L' => 'M' } }; hash{i}{J} = 'K' Each element of @array: - e - ARRAY(0x804c8d4) - c - d - a - b - i - HASH(0x806024c) Dump of hash as an array => $VAR1 = [ 'e', [ 'F', 'G', 'H' ], 'c', 'd', 'a', 'b', 'i', { 'J' => 'K', 'L' => 'M' } ]; Dump of hash as a hash => $VAR1 = { 'e' => [ 'F', 'G', 'H' ], 'c' => 'd', 'a' => 'b', 'i' => { 'J' => 'K', 'L' => 'M' } }; hash{i}{J} = 'K'

I wanted to see what happened when the hash got interpreted as an array, and then back into a hash again.  No problem, you can treat it as an array, then treat that array as a hash, and it's all still there in the same original format (as witnessed both by dumping the structure with Data::Dumper, and by accessing $hash{i}{J}).

So when you say that doesn't work if the hash has to be more than one level deep, what part do you think isn't working?


s''(q.S:$/9=(T1';s;(..)(..);$..=substr+crypt($1,$2),2,3;eg;print$..$/

Replies are listed 'Best First'.
Re^2: enabling OO and non-OO access to the same module using a hash reference
by sgt (Deacon) on Jan 15, 2007 at 22:16 UTC

    Hi, I was not surprised:) perl passed a flat list of "aliases" so it does not matter if the list comes from hash or array. Still "my assignment" just creates a shallow copy, so one should be aware of it. In a context of options (which are treated read-only) this should not be problematic

    hth --stephan