in reply to What's the Right Way to declare constants in packages?

'twas bespoken by Adam:  The real trade off is that constants declared as subs are, well, subs. They aren't scalars, you can't put them in strings and such

But we can in fact place sub output in strings:

sub pi { 'apple 3.1415936535897532'; } my $str = "I like breadnbutter. I like toasted ham. I like @{[pi]}"; print $str, $/;

output

I like bread and butter. I like toast and jam. I like pi

Acknickulous Acknowledgements

runrig and fastolfe actually coached me through this... and I think merlyn conceived that this should be a part of Perl so we owe him a big slap on the back.

Replies are listed 'Best First'.
RE: You can do string interpolation on sub output
by Adam (Vicar) on Oct 27, 2000 at 22:34 UTC
    First off, your program,
    sub pi { 'apple 3.1415936535897532'; } my $str = "I like breadnbutter. I like toasted ham. I like @{[pi]}"; print $str, $/;
    When run, prints:
    I like breadnbutter. I like toasted ham. I like apple 3.14159365358975 +32
    not
    I like bread and butter. I like toast and jam. I like pi
    Which is what your post said. But I think that's what you meant, so its ok. My real problem is that you are jumping through several hoops to do something that is trivial with a scalar:
    sub pi { 'apple 3.1415936535897532'; } my $Nov_Pi = 'pumpkin pie'; # Make anonymous array ref with output of pi(). Then de-ref the array. my $str = "I like breadnbutter. I like toasted ham. I like @{[pi]}"; # Concatenate a scalar. my $Nov_str = "I also like $Nov_Pi"; print $str, $/, $Nov_str, $/;
RE: You can do string interpolation on sub output
by Fastolfe (Vicar) on Oct 27, 2000 at 22:34 UTC
    Note that you are far better off breaking out of the string instead of interpolating in this fashion, because Perl has to put your subroutine's output into an array reference, de-reference it, then string-ify it. It's far more efficient to do this:
    my $str = "I like ... I like " . pi;
RE: You can do string interpolation on sub output
by myocom (Deacon) on Oct 27, 2000 at 22:29 UTC

    ObMathNitpick: Not that it has much bearing on your script, but the 'apple pi' pun would be better as 'apple 3.1415926535897932...'

      3.14159265358979323846264338327950288419716939 937510582097494459230781640628620899862803482 534211706798214808651328230664709384460955058 ...

      Courtesy of www.wpdpi.com