Monday, June 27, 2005

Pushing into an anonymous array ref

I wanted to have a data structure like:
$foo{bar}[0] = "baz";
and subsequently
$foo{bar}[1] = "baz2";
$foo{bar}[2] = "baz3";
...

I'm reading this stuff from a file and was looking to just get it into the array without having to worry about the index.

I found that the push function works beautifully for this purpose

push(@{$foo{bar}},"foo2");
push(@{$foo{bar}},"foo3");

Unfortunately when you go to print the typical
print "@array\n"; doesn't work in this regard so you need to use a double loop to get all of the elements in your anonymous array out.

foreach $key (keys %foo) {
print "$key = ";
foreach $i (@{$foo{$key}}) {
print "$val";
}
print "\n";
}

0 Comments:

Post a Comment

<< Home