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 Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Pushing a hash into an array and accessing 1

Status
Not open for further replies.

sloppyhack

Technical User
Apr 17, 2001
111
0
0
US
I have been trying to get a file into memory to using in processing data. Here is my sample code.

opendir (INPUT3, "/GHX Data Processing/Reference Files/AllSource Export/");
@allexport = readdir INPUT3;
closedir INPUT3;
foreach $allexport (@allexport) {
if ($allexport =~ /\.txt/) {
open (ALLSOURCE, "/GHX Data Processing/Reference Files/AllSource Export/$allexport") || warn "cannot open AllSource Export File: $!"; #open AllSource export
my @allkeys;
my @alldata;
while (<ALLSOURCE>) {
chomp;
my @fields = split /\t/;
if ($. == 1) {
@allkeys = @fields;
next;
}
my %allhash = ();
@allhash{@allkeys} = @fields;
push @alldata, \%allhash;
}
}
}
print &quot;$#alldata&quot;; #prints -1
print &quot;$alldata[34]{'OrgID'}&quot;; #I know this value exists on this line of the source file but prints nothing

I am certain the hash is being set up properly. I am either pushing the hash into the array incorrectly or calling to the array incorrectly.

PLEASE HELP!!! This is driving me nuts.

Bryant
Boulder CO
 
Hi!
You push in array hash REFERENCES, and must call its as references. The right it below:

print &quot;$alldata[34]->{'OrgID'}&quot;;

Best regards :)
 
I tried that too. It's still null. The fact that there are 135260 lines in the source file and &quot;$#alldata&quot; is null makes me think the array is not populated with the hashes as it should be. This is really driving me nuts. More suggestions please!!!

Thanks
Bryant
 
Try replacing the following lines:

my %allhash = ();
@allhash{@allkeys} = @fields;
push @alldata, \%allhash;

with:
Code:
for ($i=0; $i<=$#allkeys; $i++) {
    push @{ $alldata{$allkeys[$i]} }, $fields[$i];
}
And do the following for the prints.
Code:
for ($i=0; $i<=$#allkeys; $i++) {
    print &quot;$#{$alldata{$allkeys[$i]}}\n&quot;;
}
print &quot;$alldata{'OrgID'}[34]&quot;;
 
Thanks. My problem was that I had declared a variable inside a block with &quot;my&quot; and tried to use that same variable outside of the loop. It works ok now. I certainly appreciate the suggestion though. This message board is the best!!!!
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top