Home: Perl Programming Help: Intermediate:
Opening files with hash array values



Griff
New User

Jul 31, 2011, 12:49 AM


Views: 2469
Opening files with hash array values

Just wondering if someone can help me understand why the following doesn't work when trying to open files using Hash array values. Very frustrating.

my %FileHandles = (
SUBHIST => [$subscriberHist],
SUBDUPE => [$subscriberDupe],
SUBCLN => [$subscriberCln],
SUBDISC => [$subscriberDisc]
);

Open_Files(\%FileHandles);

sub Open_Files {
my $fileHandles = shift;
foreach $label (keys %{$fileHandles}) {
open (my $label, @{${$fileHandles}{$label}})
}
}


BillKSmith
Veteran

Jul 31, 2011, 5:35 AM


Views: 2456
Re: [Griff] Opening files with hash array values

You need the first element of the array, not the whole array.


Code
  

open( my $label, ${ ${$fileHandles}{$label} }[0] );


Good Luck,
Bill


FishMonger
Veteran / Moderator

Jul 31, 2011, 7:56 AM


Views: 2451
Re: [Griff] Opening files with hash array values

What do each of those vars in %FileHandles hold? Are they simple scalars holding the full path to the file to be opened, or are they references to lists of file paths?

Why are you assigning them as array references?

Given the current initialization of the foreach loop, you can't use $label for the filehandle.

Since that hash doesn't contain filehandles, it doesn't make sense to name it that way. That only servers to confuse the reader as to what the hash holds.


Griff
New User

Jul 31, 2011, 3:47 PM


Views: 2405
Re: [BillKSmith] Opening files with hash array values

Bill,

Many thanks, unfortunatley no good. I still get the same error.

Can't use string ("SUBDISC") as a SCALAR ref while "strict refs" in use at...

It keeps complaining about the file handle not the file itself.

Regards

Paul


Griff
New User

Jul 31, 2011, 3:52 PM


Views: 2404
Re: [FishMonger] Opening files with hash array values

The values in %FileHandles are file lables and file names, not references.

The variables $subscriberHist etc contain file names not references.

When you say the hash doesn't contain file handles can you advise on how this should be done.

The error I keep getting is below.

Can't use string ("SUBDISC") as a SCALAR ref while "strict refs" in use...


FishMonger
Veteran / Moderator

Jul 31, 2011, 9:13 PM


Views: 2373
Re: [Griff] Opening files with hash array values


Code
my %files = ( 
SUBHIST => $subscriberHist,
SUBDUPE => $subscriberDupe,
SUBCLN => $subscriberCln,
SUBDISC => $subscriberDisc,
);

my %file_handle;
create_filehandles(\%files);

sub create_filehandles {
my $files = shift;
foreach my $label ( keys %$files ) {
open $file_handle{$label}, '<', $files{label}
or die "can't open '$files{$label}' for reading $!";
}
}



(This post was edited by FishMonger on Jul 31, 2011, 9:14 PM)