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

I am using Class::ObjectTemplate to create a bunch of classes. Having created the objects, which get constructed by making several SQL queries to a database, I want to access some of their attributes and output them embedded in HTML.
print qq(<TD>$obj->attr1()</TD>\n);
This however results in the following being printed
<TD>DirectEntry=SCALAR(0x818e97c)->attr1()</TD>
If I however assign the result of the method call to a variable then all is well
my $attr1 = $obj->attr1() print qq(<TD>$attr1</TD>\n);
The result is as I expect
<TD>ITY101</TD>
My question is how can I avoid having to assign the result of the method call to a local variable before printing it ?

Replies are listed 'Best First'.
Re: Printing the result of calling an instance method
by davorg (Chancellor) on Apr 02, 2001 at 12:09 UTC

    Subroutine calls don't interpolate in strings unless you do a bit of particularly kludgy magic. Try this:

    print qq(<TD>@{[$obj->attr1()]}</TD>\n);

    Very nasty. But it works :)

    --
    <http://www.dave.org.uk>

    "Perl makes the fun jobs fun
    and the boring jobs bearable" - me

      I know why it works, but I have always wondered why people do that trick. Personally I find it works just fine to use string concatenation, and that is a lot less syntax as well. Besides which, the trick puts the function call in array context which is usually what I didn't mean.

      Now you know better. But most people shown the above are going to get an interesting surprise when comparing:

      print "The current date is @{[localtime()]}.\n"; print "The current date is ".localtime().".\n";
      So, even though using that shows you are an uber-cool Perl hacker, I don't...

        Oh, you're absolutely right. As I said above, it's very nasty - for all kinds of reasons.

        As for the list/scalar context problem, you could do something like:

        print "The current date is @{[scalar localtime]}.\n";

        But I really wouldn't recommend it :)

        --
        <http://www.dave.org.uk>

        "Perl makes the fun jobs fun
        and the boring jobs bearable" - me

      davorg, Thanks your a star, I really just wanted to output the attribute from within a HERE doc. Your solution is perfect ++ to you
Re: Printing the result of calling an instance method
by arturo (Vicar) on Apr 02, 2001 at 17:28 UTC

    Another way to do it besides the wacky @{[$obj->method]} solution and concatenation => use printf :

    printf("<td>%s</td>", $obj->attr1);

    Philosophy can be made out of anything. Or less -- Jerry A. Fodor

Re: Printing the result of calling an instance method
by busunsl (Vicar) on Apr 02, 2001 at 10:44 UTC
    You have to concatenate the strings with the result of the method.

    Try this:

    print "<TD>" . $obj->attr1() . "</TD>\n";