in reply to Reliably simulating 5.10 say()

Hello hlc, and welcome to the Monastery!

This is one case where prototypes are actually useful. From perlsub#Prototypes:

As the last character of a prototype, or just before a semicolon, a @ or a %, you can use _ in place of $: if this argument is not provided, $_ will be used instead.

Hence:

#! perl use strict; use warnings; sub say (_) # <-- ADD THIS { print @_, "\n"; } my @a = qw(1 2 3); say for @a;

Output:

0:16 >perl 1151_SoPW.pl 1 2 3 0:16 >

Hope that helps,

Athanasius <°(((><contra mundum Iustus alius egestas vitae, eros Piratica,

Replies are listed 'Best First'.
Re^2: Reliably simulating 5.10 say()
by LanX (Saint) on Feb 08, 2015 at 15:08 UTC
Re^2: Reliably simulating 5.10 say()
by choroba (Cardinal) on Feb 08, 2015 at 15:57 UTC
    Unfortunately, the _ prototype was added in 5.10 (check perl5100delta), the same version where say was added.
    لսႽ† ᥲᥒ⚪⟊Ⴙᘓᖇ Ꮅᘓᖇ⎱ Ⴙᥲ𝇋ƙᘓᖇ
Re^2: Reliably simulating 5.10 say()
by ikegami (Patriarch) on Feb 08, 2015 at 15:41 UTC

    It actually behaves like

    sub say (_) # <-- ADD THIS { local $\ = "\n"; print @_; }
Re^2: Reliably simulating 5.10 say()
by hlc (Initiate) on Feb 08, 2015 at 14:18 UTC
    Thanks, but that gives me the error:
    Not enough arguments for main::say at a.pl line 10, near "say foreach +" Malformed prototype for main::say: _ at a.pl line 13.
      Perhaps it is a relatively new feature. Which version of Perl are you running?

      The same code works for me in Perl 5.14.

      Update: I did not see it before I posted the above, but several people have responded below that it is a feature that was introduced in version 5.10.

      Je suis Charlie.
      It works perfectly for me. Please show the exact code that you tested and gave this error.

      Je suis Charlie.
        #!/usr/bin/env perl + + use strict; + use warnings; + + sub say (_) { + print @_, "\n"; } + + my @a = qw(1 2 3); + + # using implicit $_ does not work: + say foreach (@a); + + # ...and of course explicit $_ works. + say $_ foreach (@a); + + # works: + say "uncle bob";
        The error for above:
        Illegal character in prototype for main::say : _ at a.pl line 6. Not enough arguments for main::say at a.pl line 13, near "say foreach +" Malformed prototype for main::say: _ at a.pl line 16.