Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Returning an array from an associative array

Status
Not open for further replies.

grittyminder

IS-IT--Management
Oct 18, 2005
53
JP
I'm assigning an array as a value to an associative array (they key is a string). When I try to get the array value using the key... well, it seems I can get it but I can't assign it. Here's what I wrote:

foreach $key (keys %nameTable){
my $outputStr = "";
my @valueArray = @nameTable{$key};
#print "VALUEARR: " . @valueArray . "\n";
#print "VALUEARR: " . @nameTable{$key} . "\n";
for(my $i=0; $i < @valueArray; $i++){
my $value = $valueArray[$i];
$outputStr = $outputStr . $value;
if($i < @valueArray-1){
$outputStr = $outputStr . $DELIMETER;
}
}
print "$outputStr\n";
}

So the problem is that @nameTable{$key} = 8 (i.e. the length of the array associated with $key) whereas @valueArray = 1. It seems that the array being returned from %nameTable is not being assigned correctly to @valueArray. What is going on?
 
you probably want to do this if the values of the hash are really arrays and not strings:

my @valueArray = @{$nameTable{$key}};
 
Thanks for the help. I replaced the following line:

my @valueArray = @nameTable{$key};

with what you suggested:

my @valueArray = @{$nameTable{$key}};

but now I get this error:

Can't use string("8") as an ARRAY ref while "strict refs" in use.

So it appears that something is returning the number of items in the table instead of the value? (I'm just guessing here, obviously I'm no perl expert). What's wrong here?
 
'8' is the the number of items in the array, actually.
 
do this:

in your script add:

use Data::Dumper;

then later in the script:

print Dumper(%nameTable);

this way we can look at the data and see how it's really structured instead of making guesses.
 
Wow, okay, I tried what you suggested (the data dump thing) and I found out that the value being assigned wasn't an array at all (it was the length of the array). So I guess my assumptions were all wrong.

So I changed the following line:

$nameTable{$name} = @output;

...to this:

@{$nameTable{$name}} = @output;

...and now everything seems to work. Thanks for the help. I don't think there is any way I would have been able to figure this out on my own.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top