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

I know one shouldn't use use a variable variable name, so I decided to put my variable variable names in a hash instead, thus:
#!/usr/bin/perl use strict; use warnings; my %intros = (); open my $fh, '<', 'big_pipe_delimited_file' or die $!; while (<$fh>) { my ($intro) = /^(.*?)\|/; $intros{$intro} = 1; } my %introsh = (); for (keys %intros) { open $introsh{$_}, '>', 'big_pipe_delimited_file_' . $_ or die $!; } seek($fh, 0, 0) or die $!; while (my $line = <$fh>) { my ($intro) = $line =~ /^(.*?)\|/; print $introsh{$intro} $line; }
Perl objects to my use of $introsh{$intro} in the print statement: Scalar found where operator expected at foo.pl line baz, near "} $line" (Missing operator before $line?). What can I do instead?

Replies are listed 'Best First'.
Re: using a variable name for a filehandle
by poj (Abbot) on Sep 18, 2015 at 15:11 UTC

    See 3rd paragraph in print
    poj

Re: using a variable name for a filehandle
by ateague (Monk) on Sep 18, 2015 at 15:37 UTC
    Just to expand what poj said:
    If you're storing handles in an array or hash, <...> you will have to use a block returning the filehandle value instead

    Before:
    print $introsh{$intro} $line;

    After:
    print {$introsh{$intro}} $line;

Re: using a variable name for a filehandle
by msh210 (Monk) on Sep 18, 2015 at 15:40 UTC
    Many thanks, poj, ateague. Should've thought to look at print.