key as filehandle error

B

Bill

I'm trying to use a hash key as a filehandle like so.

#!/usr/local/bin/perl
use strict;

my %buf = (
'F00' => 'foo.dat'
);

&open_files();

exit 0;

sub open_files {
while(my($k,$v)=each(%buf)) {
open ($k, ">$v") || die $!;
}
}


But, I get the following error:
Can't use string ("F00") as a symbol ref while "strict refs" in use at
../try.pl line 14.

I've tried varouis things like \*FOO, *$k ... nothing seems to work.
UNLESS I take out strict, then it works.

Anyone know what's happening here.

Thanks,
Bill
 
J

Joe Smith

Bill said:
I'm trying to use a hash key as a filehandle like so.

#!/usr/local/bin/perl
use strict;

my %buf = (
'F00' => 'foo.dat'
);

&open_files();

exit 0;

sub open_files {
while(my($k,$v)=each(%buf)) {
open ($k, ">$v") || die $!;
}
}

If you're using a reasonably recent version of perl, you can use this:

#!/usr/bin/perl
use strict;
use warnings;

my %buf = (
'F' => 'foo.dat',
'B' => 'bar.dat',
);

{ # Bare block to delimit scope of %fh
my %fh = open_files(%buf);
print {$fh{B}} "One line to file 'B' ($buf{B})\n";
print {$fh{F}} "Another to file 'F' ($buf{F})\n";
} # All %fh file handles get closed here
exit 0;

sub open_files {
my %filenames = @_;
my %filehandles;
while(my($k,$v)=each(%filenames)) {
open $filehandles{$k}, '>', $v or die "Cannot open '$k' file $v: $!\n";
}
%filehandles;
}

-Joe
 
N

nobull

I'm trying to use a hash key as a filehandle like so.

#!/usr/local/bin/perl
use strict;

my %buf = (
'F00' => 'foo.dat'
);

&open_files();

exit 0;

sub open_files {
while(my($k,$v)=each(%buf)) {
open ($k, ">$v") || die $!;
}
}


But, I get the following error:
Can't use string ("F00") as a symbol ref while "strict refs" in use at
./try.pl line 14.

I've tried varouis things like \*FOO, *$k ... nothing seems to work.
UNLESS I take out strict, then it works.

Anyone know what's happening here.

Yes, you are trying to use a symbolic reference.

Either stop trying to use a symbolic reference or tell Perl that you
really want to.

You can't use \*FOO as a hash key - or rather if you try it'll be
converted into a string like 'GLOB(0x8105afc)' because hash keys are
strings.

There is such a thing as Tie::RefHash that would allow you to use a
reference as a hash key but I wouldn't recommend it.

My advice is take a step back and decide what it is you were trying to
achive by using filehandles as hash keys and come up with another way
to do it (probably involoving autovivified dynamic file handles).

This newsgroup does not exist (see FAQ). Please do not start threads
here.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,534
Members
45,008
Latest member
Rahul737

Latest Threads

Top