fireblood has asked for the wisdom of the Perl Monks concerning the following question:
Dear wise ones,
A problem that I am having is illustrated by the following simplified code:
print STDERR "This is line 1.\n"; my $var = STDERR; print $var "This is line 2.\n"; my %hash = (key => STDERR); print "The value of the hash variable is $hash{key}.\n"; my $which_stream = $hash{key}; print $which_stream "This is line 3.\n"; #print $hash{key} "This is line 4.\n";
Note that the last instruction is commented out.
When I run the code as shown, I get the following:
This is line 1. This is line 2. The value of the hash variable is STDOUT. This is line 3.
I can confirm by redirection of the output from the above script that it is indeed writing to STDERR, not the default STDOUT, so everything looks good so far.
But if I uncomment that last instruction I get the following:String found where operator expected at test.pl line 12, near "} "This + is line 4.\n"" (Missing operator before "This is line 4.\n"?) syntax error at test.pl line 12, near "} "This is line 4.\n"" Execution of test.pl aborted due to compilation errors.
So, syntactically it looks as if Perl accepts
print $output_stream $test_message;but not
print $hash{output_stream} $test_message;Is there any way, such as through the use of a pragma, to get Perl to accept the last version of the print instruction without converting the hash-based value to a simple scalar value? (This is for This is perl 5, version 34, subversion 0 (v5.34.0) built for x86_64-linux-thread-multi)
The reason why this is a relevant question for me is because I am trying to develop a function in which the output print stream needs to be parameterized, e.g. STDOUT, STDERR, etc., and I am implementing it using a hash as an argument, as illustrated in Problem 10.7 – Passing by Named Parameter in the second edition of the Perl Cookbook by Tom Christiansen. All of my function works fine, including where it uses other values that are defined in the passed hash, but the fact that Perl does not accept syntax where a hash value is used in the position of a print stream specifier token is putting me in a position of having to add extra steps to convert the hash value into a simple scalar, which seems like a kludge.
Thanks much!
-FirebloodᏙᎾᏓᎪᎲᎢ
P.S.: No difference when using $hash -> key
|
---|