in reply to sprintf: using nested code

Please explain the problem you have.

This works for me:

$ perl -e 'sub double { return 2 * shift;} ; my $c = sprintf "%s\n%s\n +", "foo", double(3); print $c;' foo 6

Replies are listed 'Best First'.
Re^2: sprintf: using nested code
by Laurent_R (Canon) on Sep 14, 2015 at 20:24 UTC
    OK, I had originally missed that you are defining the sub inside the sprintf arguments (but never actually call the sub), so that sprintf will output a coderef, as in this simpler example:
    $ perl -e 'print sprintf( "%s%s", > "header" . "\n", > sub { return 3}); > ' header CODE(0x6000684c8)
    Of course, you can solve the problem by calling the coderef:
    $ perl -e 'print sprintf( "%s%s", "header" . "\n", ,sub { return 3}- +>())' header 3
    as shown by BrowserUk, but it seems to me that you are looking for complicated ways of achieving simple things.

    Why don't you define your sub separately? Or use some other way of merging your data?

    Something like that works properly:

    $ perl -e 'sub concat { my $str; for ($_[0]..$_[1]) { $str .= $_;} $st +r;} > print sprintf "%s\n%s\n", "foo", concat('a', 'e'); > ' foo abcde