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

This is a bit of a hard one to explain succinctly!

Given an object built on a hash reference:

my $self = bless( { log => undef, }, $package );

Perl won't allow you to use this!

You can't write this:

say $self->{'log'} 'Message';

This results in: String found where operator expected at ..., near "} ''" (Missing operator before ''?)

Having converted this module from package globals to OOP, I started getting bizarre crashes: "Not a CODE reference"

This, I tracked down to:

say $self->{'log'} ($detailedMessage // $message);

Here, having an object property as a direct object file handle causes Perl to defecate building materials.

It doesn't seem to be a common thing to want to do, as I'm not seeing any suggestion that anyone else is seeing this fail.

It's not a huge deal to have to copy the file handle reference into a local variable to use it with say, but it's just very odd and it would be nice to understand what it's tripping up over here.

This is perl 5, version 20, subversion 2 (v5.20.2) built for x86_64-linux-gnu-thread-multi. The code begins:

use strict; use warnings; use utf8; use 5.10.0; no warnings 'experimental::smartmatch';

Replies are listed 'Best First'.
Re: Object property not legal as direct object?
by hippo (Archbishop) on Nov 09, 2016 at 11:25 UTC

    From perldoc print:

    If you're storing handles in an array or hash, or in general whenever you're using any expression more complex than a bareword handle or a plain, unsubscripted scalar variable to retrieve it, you will have to use a block returning the filehandle value instead

    So, this works fine:

    #!/usr/bin/env perl use strict; use warnings; my $hr = { logfh => \*STDOUT }; print { $hr->{'logfh'} } "Hello Hashref\n"; my $obj = bless ($hr, 'UNIVERSAL'); print { $obj->{'logfh'} } "Hello Object\n";

      Braces? How odd. Over eight years on and Perl still has so many oddities I've yet to uncover!

      Silly me, I was overthinking it — I forgot that Perl documentation is actually decent :) (I did actually verify that print has the same problem, funnily enough.)

      Thank you.

      The book "Perl Best Practices" recommends putting braces around the filehandle in every print statement. Even when they are not needed, they make it clear that you did not forget a comma.
      Bill
Re: Object property not legal as direct object?
by dave_the_m (Monsignor) on Nov 09, 2016 at 11:24 UTC
    When using an indirect object (like print and say do), you need to enclose the object expression in braces if it's not simple, e.g.
    say {$self->{'log'}} 'Message';

    Dave.

Re: Object property not legal as direct object?
by choroba (Cardinal) on Nov 09, 2016 at 14:42 UTC
Re: Object property not legal as direct object?
by zwon (Abbot) on Nov 09, 2016 at 22:03 UTC
    Why not
    $self->{log}->say($message)
    I personally think it is more readable