Dan Dan - 2 years ago 327
Perl Question

illegal declaration of subroutine, perl

I'm going through a book and made the following from pieces of examples in order to answer an exercise. I may have messed something up, but it looks ok to me. I get the error: Illegal declaration of subroutine main::read_file at x3.pl line 31. I'm not sure what is wrong here and would appreciate help. The author wants use to use croak so if that is messed up please include it in the solution.

use strict;
use warnings;

sub croak { die "$0: @_: $!\n" }

sub read_file {
my $file = shift;
open (FILE, $file) || croak "Couldn't open $file";

while (my $line = <FILE>) {
read_line $line;

sub read_line {
our %hash;

my @list = split " ", shift;
foreach my $word (@list) {

sub print_has {
our %hash;

my @list = keys %hash;
print "@list\n";

sub read_file @ARGV
sub print_has

Thank you ikegami for the answer. I am now getting an error I did not expect:

Can't locate object method "read_line" via package "dog
" (perhaps you forgot to load "dog
"?) at x3.pl line 11, <FILE> line 1.

dog is the first line of the text file I want to read.

Answer Source

This is wrong:

sub read_file @ARGV
sub print_has

I think you're trying to call the subs? Subroutine calls don't use the sub keyword.

read_file @ARGV;

There are a number of bad practices in the code, one of which prevents the code from running. You should subject it to a code review.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download