http://qs321.pair.com?node_id=11147905

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

Dear fellow monks - once again I seek your wisdom.

Is there a way to embed the return value of a sub directly in a qq{ ... } statement? Something like

sub b{ return("bar"); } print( qq{ monk magic against foo b() } );

I've tested function references and high voltage, but I can't bring it to life.

Replies are listed 'Best First'.
Re: sub return value in qq{}
by choroba (Cardinal) on Nov 02, 2022 at 09:54 UTC
    References (and dereferences) should work:
    print qq{ monk magic ${ \b() } };

    You can also use an array reference, which is great if you need more than one thing:

    print qq{ monk magic @{ [b(), b()] } };

    map{substr$_->[0],$_->[1]||0,1}[\*||{},3],[[]],[ref qr-1,-,-1],[{}],[sub{}^*ARGV,3]
Re: sub return value in qq{}
by johngg (Canon) on Nov 02, 2022 at 09:55 UTC

    Babycart operator!

    johngg@aleatico:~$ perl -Mstrict -Mwarnings -E 'say q{}; sub bar {return q{bar} } say qq{Drink at the @{ [ bar() ]}};' Drink at the bar

    Cheers,

    JohnGG

Re: sub return value in qq{}
by davido (Cardinal) on Nov 02, 2022 at 14:16 UTC

    The dereferenced arrayref technique works fine: "a string @{[foo()]}\n". But it's a little magical; it requires some tribal knowledge or testing for a reader of the code to understand what is happening.

    Perl also provides printf, which is well documented and should be clearer for a reader:

    sub foo { return "bar" } printf "foo returns %s\n", foo();

    Additionally, there are a lot of template systems available to Perl. Template::Toolkit, Text::Template, Mojo::Template, Template::Tiny, and many others. Here is an example using Template::Toolkit:

    #!/usr/bin/env perl use strict; use warnings; use Template; sub foo {return "bar"} my $output; Template ->new ->process( \"foo returns [% f %]\n", {f => foo()}, \$output, ); print $output;

    This code works as-is with Template::Tiny if you just replace any mention of Template with Template::Tiny.


    Dave

Re: sub return value in qq{}
by jwkrahn (Abbot) on Nov 02, 2022 at 16:32 UTC

    You could always use printf / sprintf :

    sub b{ return("bar"); } printf( qq{ monk magic against foo %s }, b() );
Re: sub return value in qq{}
by LiquiNUX (Novice) on Nov 02, 2022 at 10:01 UTC
    Wow, that is a quick reply. Thank you for sharing your wisdom. Greetings from Berlin.