in reply to Spotting an empty array as argument

Here's something that AFAICT meets your requirements, but since it's Friday evening I might be missing a test case for which it fails*. But as I mention here, it's really still just an approximation.

sub mysay (;+@) { return say $_ unless @_; if ( ref $_[0] eq 'ARRAY' ) { unshift @_, @{shift()} } elsif ( ref $_[0] eq 'HASH' ) { unshift @_, %{shift()} } say join "\n", @_; }

* Update: Of course, just two minutes after posting I thought of one: say \@x would normally print ARRAY(0x...), this function dereferences it. Like I said, an approximation! I think you might be better off just biting the bullet and writing say join "\n", ...; ...

Test cases...

#!/usr/bin/env perl use warnings; use strict; use feature 'say'; $_ = "Foo"; my @x = ("x", "y"); my @y = (); my $z = "Bar"; my %h = ( abc => 123 ); { local $, = "\n"; say; say "------"; say $z; say "------"; say "Hello"; say "------"; say "cool", "world"; say "------"; say @x; say "------"; say "foo", @x; say "------"; say @y; say "------"; say %h, "xyz"; say "######"; } sub mysay (;+@) { return say $_ unless @_; if ( ref $_[0] eq 'ARRAY' ) { unshift @_, @{shift()} } elsif ( ref $_[0] eq 'HASH' ) { unshift @_, %{shift()} } say join "\n", @_; } mysay; say "------"; mysay $z; say "------"; mysay "Hello"; say "------"; mysay "cool", "world"; say "------"; mysay @x; say "------"; mysay "foo", @x; say "------"; mysay @y; say "------"; mysay %h, "xyz"; say "######";

Replies are listed 'Best First'.
Re^2: Spotting an empty array as argument
by LanX (Saint) on Mar 26, 2021 at 22:34 UTC
    good try :) But ...

    DB<262> sub mysay (;+@) { print @_ } DB<263> mysay 1,2,3 123 DB<264> mysay 1..3 DB<265> mysay 1..3,4..6 456 DB<268>

    It's enforcing scalar context on the first argument, and this is one of the unfortunate cases where an operator is changing it's meaning on context. :(

    Cheers Rolf
    (addicted to the Perl Programming Language :)
    Wikisyntax for the Monastery

      mysay 1..3

      Ah, a very good point, thanks!

      Chuma: This once again underlines the fact that, unfortunately (!), you're probably not going to get everything you want here. Perhaps it would also make sense to take a step back and explain what you want to use this function for? And if you think about it again, do you really need to default to $_? Or could you split this into two different functions? etc.