perladvent / perldotcom

The source code for Perl.com website
https://www.perl.com
77 stars 80 forks source link

Error using references #335

Closed ghost closed 2 years ago

ghost commented 2 years ago

About Pearl Design Patterns, Part 2 by Phil Crow, I tried to run Strategy example: list all files in the current directory but I get this error: Undefined subroutine &main::./a.pl called at file.pl line 22.

This is line 22 push @retval, $path if &$callback($path);

And this is the complete code:

!/usr/bin/perl

use strict; use warnings;

my @files = find_files(\&is_hidden, "."); local $" = "\n"; print "@files\n";

sub is_hidden { my $file = shift; $file =~ s!.*/!!; return 0 if ($file =~ /^./); return 1; }

sub find_files { my $callback = shift; my $path = shift; my @retval;

no strict 'refs';
push   @retval, $path if &$callback($path);
return @retval unless (-d $path);

# identify children
opendir DIR, $path or return;
my @files = readdir DIR;
closedir DIR;

# visit each child
foreach my $file (@files) {
    next if ($file =~ /^\.\.?$/);  # skip . and ..
    push @retval, find_files("$path/$file", $callback);
}

return @retval;

}

What seems to be the trouble?

I am using Strawberry for Windows.

This is perl 5, version 32, subversion 1 (v5.32.1) built for MSWin32-x64-multi-thread

Beforehand thanks a lot for your valuable help.

ghost commented 2 years ago

I have found out which was the issue

Lines of code later, there was the problem. The same function was invoked with the parameters in the wrong order

It was like this

push @retval, find_files("$path/$file", $callback);

It must be like this

push @retval, find_files($callback, "$path/$file");