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

Hi Monks,
I currently found an example of CPAN Module IO::Multiplex which doesn't work the way it's printed in the module-pod.

Here comes the code that doesn't work:

package Player; my %players = (); sub new { my $package = shift; my $self = bless { mux => shift, fh => shift } => $package; # Register the new player object as the callback specifically for # this file handle. $self->{mux}->set_callback_object($self, $self->{fh}); print $self->{fh} "Greetings, Professor. Would you like to play a +game?\n"; ...
Now here is the bug (it is really a bug?) the  print $self-{fh} "whatever"; brings up the error:
String found where operator expected at server.pl line 42, near "} "Gr +eetings, Professor. Would you like to play a game?\n"" Missing operator before "Greetings, Professor. Would you like to play + a game?\n"?) syntax error at server.pl line 42, near "} "Greetings, Professor. Woul +d you like to play a game?\n""
After changed it to:
my $fh = $self->{fh}; print $fh "Greetings .....";
all is fine.

The question is now, is this in general not possible to print to a hash-stored-handle by deref it during the print command, or am I missing something ?

Thnx

----------------------------------- --the good, the bad and the physi-- -----------------------------------

Replies are listed 'Best First'.
Re (tilly) 1: print on a hash-stored-handle
by tilly (Archbishop) on Jun 25, 2001 at 17:00 UTC
    It is in general not possible. I forget the exact logic, but it is nasty enough that Perl can't figure out what you mean and fails to figure it out.

    The solutions are to either create a temporary variable or to turn the print into a method call using IO::Handle. I prefer using the temporary variable. YMMV.

Re: print on a hash-stored-handle
by bwana147 (Pilgrim) on Jun 25, 2001 at 17:42 UTC

    The CookBook says "only simple scalar variables, not expressions or subscripts into hashes or arrays, can be used with build-ins like print, printf or the diamond operator. ... you get around this by using a block and an expression where you would place the filehandle". In your case, that's:

    print { $self->{fh} } "Greetings, Professor.";

    --bwana147