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

Hello All,

This may seem very basic and simple question but still I am forced to ask.

I have an array containing many strings. I want to use those strings as file handlers. But when I try to use them it throws:

Can't use string ("my-test-string") as a symbol ref while "strict refs"

How can I make it work using both 'use strict' and also being able to use strings as file handlers.

Replies are listed 'Best First'.
Re: Using Strings as File Handlers
by Corion (Patriarch) on Jan 04, 2010 at 09:03 UTC

    Do you really want to use strings as file handles? Why? The following works under any Perl since 5.6.0:

    open my $fh, '<', $filename or die "Couldn't open '$filename': $!"; push @filehandles, $fh;

    If you don't want to use lexical filehandles but keep on using bareword filehandles (which is what "string filehandles" are), then you'll have to switch off strict, because that's one thing that it forbids, and for good reason IMO.

Re: Using Strings as File Handlers
by Khen1950fx (Canon) on Jan 04, 2010 at 09:18 UTC
    There is another way, albeit not as good as Corion's. See: perlfaq5. Try this:
    #!/usr/bin/perl use strict; use warnings; my $string = 'my-test-string'; open(my $fh, '>', \$string) or die "Could not open string for writing"; print $fh "my-test-string\n"; open($fh, '<', \$string) or die "Could not open string for reading"; my $x = <$fh>; print $x, "\n";

      Oh - that is a different interpretation of the question, but it might well be that I misunderstood the question. This solution will use a string instead of a file on disk and access it as a file handle.