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

Hi,
I need help, please.

I’m trying to run the following code:

use strict; use Carp; open (File_1,">c:/File1.txt") || die "Can't open File1 for writing\n"; open (File_2,">c:/File1.txt") || die "Can't open File2 for writing\n"; my $variable = 1; my $fileName = "File_".$variable; print $fileName "Hello\n";
But I’m getting the following error message:
Can't use string ("File_1") as a symbol ref while "strict refs" in use + at….
Is the a way to use a variable file name with strict refs on??

Thanks.

Replies are listed 'Best First'.
•Re: Bypassing strict refs
by merlyn (Sage) on Jan 23, 2003 at 17:12 UTC
    You really don't want to bypass use strict. It's saving you from later headaches.

    Any time you have a sequentially named series of variables, it's a good clue that they are related, and if they're related, they belong in a common data structure, because at some point, you will probably want to iterate over all or some of them.

    In your particular case, I'd suspect you want the two filehandles to be in an array. However, Perl doesn't allow traditional filehandles to be moved around like data, so you have to create fairly modern filehandle objects instead:

    use strict; use Carp; use IO::File; my @handles; push @handles, IO::File->open(">c:/File1.txt") || die "Can't open File +1 for writing\n"; push @handles, IO::File->open(">c:/File2.txt") || die "Can't open File +2 for writing\n"; for my $variable ( 0..1 ) { # write this to both files print { $handles[$variable] } "Hello\n"; }

    -- Randal L. Schwartz, Perl hacker
    Be sure to read my standard disclaimer if this is a reply.

Re: Bypassing strict refs
by thezip (Vicar) on Jan 23, 2003 at 18:31 UTC

    I usually do something (purely cosmetic) like:

    use strict; use warnings; my $outfilename = "outfilename.txt"; # Use a variable for the outfile handle my $ofh; open($ofh, ">$outfilename") or die qq(Couldn't open file "$outfilename +" for writing\n); ... insert more code here close $ofh;
    Where do you want *them* to go today?
Re: Strict refs
by davorg (Chancellor) on Jan 23, 2003 at 17:03 UTC

    Well, you could do something like:

    use strict; use Carp; my @files; open ($files[0], ">c:/File1.txt") || die "Can't open File1 for writing\n"; open ($files[1], ">c:/File1.txt") || die "Can't open File2 for writing\n"; my $variable = 0; print { $files[0] } "Hello\n";

    But it might be cleaner to switch to using IO::File.

    --
    <http://www.dave.org.uk>

    "The first rule of Perl club is you do not talk about Perl club."
    -- Chip Salzenberg