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

I copied the following code straight from the "Learning Perl" book by Randal L. Schwartz. But I keep getting the following message: " Illegal declaration of subroutine main::check_required at c:\chapter 4\isametask3.pl line 12. Can someone solve this? thank you,

use 5.012; my @gilligan=qw(red_shirt hat lucky_socks water_bottle); &check_required items ("gilligan",@gilligan); sub check_required items { $who=shift; %whos_items=map {$_,1} @_; @required=qw(preserver sunscreen water_bottle jacket); for my $item(@required){ unless($whos_items{$item}){ print "$who is missing $item.\n"; } } }

Replies are listed 'Best First'.
Re: Illegal declaration of subroutine Error
by kcott (Archbishop) on Dec 01, 2013 at 02:18 UTC

    G'day ostra,

    My guess would be that "check_required items" is supposed to be "check_required_items". Note the second underscore ('_') and that this occurs in two places ("&check_required items ..." and "sub check_required items ...").

    You haven't indicated which edition of the book you're referring to (I believe there's quite a few). You haven't provided a link to the book or its example source code (if such exists). Consequently, I'm not in position to check this for you.

    It may be a typographical error. It might just be a printing error/defect (look closely: are there possibly faint underscores where I indicated). Also, check online for any published errata.

    Finally, what you've "copied" is probably not the same as what you see in the book: I imagine it has at least some reasonable indentation. Unfortunately, this brings into question how close what you typed is to the original: other than whitespace it might be identical; however, my guess at a correction involves whitespace.

    -- Ken

Re: Illegal declaration of subroutine Error (no spaces in names)
by Anonymous Monk on Dec 01, 2013 at 02:03 UTC
Re: Illegal declaration of subroutine Error
by Khen1950fx (Canon) on Dec 01, 2013 at 09:53 UTC
    The first thing to do when you start a script is use strictures:
    #!/usr/bin/perl use strict; use warnings;
    When you finish the script, run it through Perl::Tidy:
    #!/usr/bin/perl -l use strict; use warnings; my (@gilligan) = qw( red_shirt hat lucky_socks water_bottle ); check_require_items( 'gilligan', @gilligan ); sub check_require_items { use strict; use warnings; my $who = shift(); my (%whos_items) = map( { $_, 1; } @_ ); my (@required) = qw( preserver sunscreen water_bottle jacket ); foreach my $item (@required) { unless ( $whos_items{$item} ) { print "$who is missing $item."; } } }
    It's easier to read, no?