bmcquill has asked for the wisdom of the Perl Monks concerning the following question:

I doing a Perl tutorial and I have a problem posed: Create a library with a function that takes in an array of numbers (of arbitrary size). The function will then calculate the average of the numbers, the total of all of the numbers added together, and a new array of numbers which is comprised of the original input numbers each divided by 2. It will then return a new list with all of that information. What I'm stuck on is how to write a script that creates the array and pass that to the library, completing the steps above. Anyone have similar examples?

Replies are listed 'Best First'.
Re: Perl Functions
by frozenwithjoy (Priest) on Mar 28, 2015 at 04:02 UTC
    Hi. What have you tried so far? Also, it might help for you to write out the logic in pseudocode and then translate each step into Perl code.
Re: Perl Functions
by LanX (Saint) on Mar 28, 2015 at 04:05 UTC
    > What I'm stuck on is how to write a script that creates the array and pass that to the library,

    something like this ?

    DB<110> @a = map { int rand 100 } 1..5 => (61, 43, 71, 44, 61)

    then call @ret=func(@a)

    Cheers Rolf
    (addicted to the Perl Programming Language and ☆☆☆☆ :)

    PS: Je suis Charlie!

Re: Perl Functions
by choroba (Cardinal) on Mar 28, 2015 at 12:11 UTC
    Here is a similar example. The library (module in Perl parlance) MedianAndDouble exports a subroutine which, surprisingly, returns the median and a list of the input numbers times two.

    Module MedianAndDouble.pm

    #!/usr/bin/perl use strict; use warnings; package MedianAndDouble; use Exporter 'import'; our @EXPORT_OK = qw{ median_and_double }; sub median_and_double { my @l = sort { $a <=> $b } @_; return ( ($l[ $#l / 2 ] + $l[ ($#l + 1) / 2 ]) / 2, map 2 * $_, @_ ) }

    Script that uses the module

    #!/usr/bin/perl use strict; use feature qw{ say }; use warnings; use MedianAndDouble qw{ median_and_double }; my @list1 = (10, 11, 12); say join ' ', median_and_double(@list1); my @list2 = (10, 11, 12, 13); say join ' ', median_and_double(@list2);

    Update: Added missing sort. Thanks oiskuu.

    لսႽ† ᥲᥒ⚪⟊Ⴙᘓᖇ Ꮅᘓᖇ⎱ Ⴙᥲ𝇋ƙᘓᖇ
Re: Perl Functions
by Anonymous Monk on Mar 28, 2015 at 08:21 UTC

    I doing a Perl tutorial and I have a problem posed:

    What tutorial, where is the link?

    I sure hope its one of these tutorials at Perl Tutorial Hub

Re: Perl Functions
by ww (Archbishop) on Mar 28, 2015 at 12:00 UTC