Search code examples
perlargumentssubroutine

Perl, Best Practices: Empty Arguments handling inside subroutine, use of $_


I ran into following code example while was reading book "Perl Best Practices by Damian Conway":

    sub fix {
        my (@args) = @_ ? @_ : $_; # Default to fixing $_ if no args provided

        for my $arg (@args) {
            print $arg;
        }

        return;
    }

Could you please help me to understand what exactly author wants to accomplish in this part of code?

my (@args) = @_ ? @_ : $_; # Default to fixing $_ if no args provided

I understand what "if" does, and it's clear for me that we will assign $_ to "@args" when user does not provide parameters for "fix() sub"

But it's not clear what is the benefit to assign $_ to @args since $_ is undef, right?

Thank you in advance.


Solution

  • @_ and $_ are two different variables, so $_ can be defined even if @_ is empty. $_ is used as the default in many functions, e.g. length or chr.

    See $_ and @_.