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

Hi everyone...

I’m trying to run the following simple code but I keep getting the error message: Undefined subroutine &main::total called at p67-1 line 4.

I’ve been trying for hours to understand why and I’m stumped. Can anyone give me a hand?

The Perl version I’m using is 5.8.1. and the code came from p.67 of Learning Perl, Schwartz, Phoenix and Foy.

Thank you, John.

#!/usr/bin/perl -w use strict; my @fred = qw{ 1 3 5 7 9 }; my $fred_total = &total(@fred); print "The total of \@fred is $fred_total.\n"; print "Enter some numbers on separate lines: "; my $user_total = &total(<STDIN>); print "The total of those numbers is $user_total.\n";

Replies are listed 'Best First'.
Re: Undefined Subroutine
by merlyn (Sage) on May 19, 2006 at 22:50 UTC
      This is one of my favorite things about this site. How awesome is it that the guy that wrote the book, can explain things for you. Hats off to you merlyn. Thanks for continuing to be a part of the monastery.

      Incidentally, anyone else wonder if clearsky (still an initiate) put 2 and 2 together yet and realized he was just conversing with the Author of his text?

      -Kevin
      my $a='62696c6c77667269656e6440676d61696c2e636f6d'; while ($a=~m/(^.{2})/s) {print unpack('A',pack('H*',"$1"));$a=~s/^.{2}//s;}
      Thank you, Randal.
Re: Undefined Subroutine
by japhy (Canon) on May 19, 2006 at 22:51 UTC
    Um, the total() function is undefined. You never defined it. You have to define a function to use it, or else include some file in your program that defines it.

    Perl has no built-in total() function (and even if it did, calling a function with a '&' in front of it forces Perl to look for a user-defined function).

    You have to write the function.


    Jeff japhy Pinyan, P.L., P.M., P.O.D, X.S.: Perl, regex, and perl hacker
    How can we ever be the sold short or the cheated, we who for every service have long ago been overpaid? ~~ Meister Eckhart
      Thank you, Jeff.
Re: Undefined Subroutine
by GrandFather (Saint) on May 19, 2006 at 22:55 UTC

    &total calls a sub called total. You don't provide one. You could use sum from the module List::Util thus:

    use warnings; use strict; use List::Util qw(sum); my @fred = qw{ 1 3 5 7 9 }; my $fred_total = sum(@fred); print "The total of \@fred is $fred_total.\n";

    Prints:

    The total of @fred is 25.

    Update: Bugger, looks like I just answered a "homework" question! :)


    DWIM is Perl's answer to Gödel
      Thank you, Grandfather.
A reply falls below the community's threshold of quality. You may see it by logging in.