kokarikomi has asked for the wisdom of the Perl Monks concerning the following question:

Hi, I have encountered this problem lately but I don't know how to solve it.
my @filez=(file1,file2); open(file1,">$path1"); open(file1,">$path2"); for (my $i=0 ; $i ; $i<$node_nb; $i++) { $file=$filez[$i]; print $file "some data"; }
I have an error with the print $file ... which says 'Can't use string ("file1") as a symbol ref while "strict refs" in use' Someone can help me with that? Thank you, R.

Replies are listed 'Best First'.
Re: Problem with File Handler
by davido (Cardinal) on Jun 10, 2004 at 19:15 UTC
    What are "file1" and "file2", typeglobs, strings, barewords? Perl doesn't know, since you didn't give any indication. So it must guess.

    It guessed an unquoted string. You then opened, bareword filehandle. What you've stored in @filez would probably suffice if you weren't using strictures, but with strictures on, you are informed that you're using a symbolic reference, which is considered illegal, and the script dies. (Updated)

    You then print to the filehandle stored in $file. But $file holds a string, not a filehandle.

    You probably want something like this:

    my @files = \( *FILE1, *FILE2 ); open FILE1, ">$path1" or die $!; open FILE2, ">$path2" or die $!; foreach my $file ( @files ) { print $file "Some data\n"; }

    Dave

Re: Problem with File Handler
by BrowserUk (Patriarch) on Jun 10, 2004 at 21:08 UTC

    If you want to use an array to hold your file handles you can do it this way.

    my @filez; open $filez[ $_ ], ">data/file$_.dat" or die $! for 0..2; for my $i ( 0..2 ) { print { $filez[ $i ] } 'somedata'; #required ^..............^ } close $filez[ $_ ] for 0..2;

    Examine what is said, not who speaks.
    "Efficiency is intelligent laziness." -David Dunham
    "Think for yourself!" - Abigail
Re: Problem with File Handler
by graff (Chancellor) on Jun 10, 2004 at 23:09 UTC
    In order to manage an array of file handles, your code will be much cleaner and clearer if you use FileHandle (which is part of the core distribution -- every perl installation has it). This way, you get to use normal scalars that are references to file handles. It's just nicer.
Re: Problem with File Handler
by calin (Deacon) on Jun 10, 2004 at 19:08 UTC

    file1 is a bareword and it's not allowed by use strict refs;. Try:

    my @filez = ('file1', 'file2');

    or

    my @files = qw/file1 file2/;

    Update: text above striked through (wrong answer). The real problem is that strict refs doesn't allow passing typeglobs by symbolic reference.