develooper Front page | perl.beginners | Postings from February 2009

Converting a string to a filehandle

Thread Next
Taylor, Andrew
February 9, 2009 04:41
Converting a string to a filehandle
Message ID:

I'm processing a file of test data that looks something like:


Each line split into an array and processed.

The first element (FH1, FH2, etc) is the name of the filehandle the
output should be printed to.

I'm trying to do something like:

use strict;
use warnings;

open (FH1, ">file1");
open (FH2, ">file2");

open (INPUT, "<inputfile");

while (<INPUT>)
...split line
...process data
...create output

  my $FH = $split_line[0]

  print $FH "$output\n";


But I get the error:
"Can't use string ("FH1") as a symbol ref while "strict refs" in use at line 387, <INPUT> line 1."

I can get round it without too much difficulty with an if statement, but
I was wondering if there was a simple way to turn a string into a
filehandle.  I've tried various things like:

my $FH = "\*$split_line[0]";
print \*$FH "$output\n";
changing the data to hold \*FH1 in the first field.

All to no avail.

The closest thing I've found is the following from the perldocs website:

	$fh =   SOME_FH;       # bareword is strict-subs hostile
	$fh =  "SOME_FH";      # strict-refs hostile; same package only
	$fh =  *SOME_FH;       # typeglob
	$fh = \*SOME_FH;       # ref to typeglob (bless-able)
	$fh =  *SOME_FH{IO};   # blessed IO::Handle from *SOME_FH

But I don't think that answers my question (or if it does, I'm too dumb
to see that answer...)

Can anyone point me in the right direction?


Capgemini is a trading name used by the Capgemini Group of companies which includes Capgemini UK plc, a company registered in England and Wales (number 943935) whose registered office is at No. 1 Forge End, Woking, Surrey, GU21 6DB.
This message contains information that may be privileged or confidential and is the property of the Capgemini Group. It is intended only for the person to whom it is addressed. If you are not the intended recipient, you are not authorized to read, print, retain, copy, disseminate, distribute, or use this message or any part thereof. If you receive this message in error, please notify the sender immediately and delete all copies of this message.

Thread Next Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at | Group listing | About