Search code examples
arraysperlsubroutine

Perl subroutines and arrays


I'm just starting out Perl (about 15 minutes ago) using a tutorial online. I made a small subroutine to test a few Perl features and would like to know if it is possible to determine at runtime if parameters that were passed to the sub' call are arrays or scalars. Let's use the sub I wrote as an example:

#!/usr/bin/perl

sub somme_prod {
    if (scalar(@_) > 1) {
        $facteur = shift(@_);
        foreach my $nb (@_) {
            $resultat += $nb
        }
        return ($resultat * $facteur);
    }
    else {
        return "ERREUR";
    }
}

print somme_prod(2, 2, 3, 7);

This is a basic sum-product subroutine which does exactly what its name says. Now, would it be possible to modify this subroutine to allow for a mix of arrays and scalars like this ?

somme_prod(2, (2,3), 7);
somme_prod(2, (2,3,7));
#...

Also, any comment on the style of Perl coding demonstrated here is much welcome. I have a background of amateur C++ coding so I may not be thinking in Perl.

Edit: I'm so sorry. I actually tried it after posting and it seems that Perl does process my sub as I want it to. Now I guess my question would be more "how does Perl know how to process this" ?

Edited code for a more Perl-ish version.


Solution

  • Yes; in Perl you can create references to arrays (or hashes, or anything else) to stuff several values into a single parameter.

    For example:

    somme_prod(2, [2, 3], 7);
    

    ...would resolve to:

    sub somme_prod {
      foreach my $arg (@_) {
        if (ref($arg) eq 'ARRAY') {
          my @values = @$arg; # dereference, e.g. [2, 3] -> (2, 3)
          . . .
        } else {
          # single value, e.g. "2" or "7"
        }
      }
    }
    

    You can read the page perldoc perlref to learn all about references.