in reply to Perl Packages Issue in a script.

Trying to put an array into a scalar doesn't make much sense. It was deemed that when you attempt to evaluate an array as a scalar, you get its length.

Other issues:

# Packagetest.pm package Packagetest; sub ReadFile { my ($fn) = @_; open(my $fh, '<', $fn) or die("Can't open file \"$fn\": $!\n"); my @recs; while (<$fh>) { chomp; my @tokens = split /\|/; push @recs, \@tokens; } return \@recs; } 1;
#!/usr/bin/perl -w use strict; use warnings; use Packagetest; my $recs = Packagetest::ReadFile("datafile"); for my $rec (@$recs) { print "Wrestlername: $recs->[0]\n"; print "Crowdreaction: $recs->[1]\n"; print "Specialmove: $recs->[2]\n"; print "\n"; }

Replies are listed 'Best First'.
Re^2: Perl Packages Issue in a script.
by Irishboy24 (Sexton) on Oct 01, 2009 at 22:38 UTC
    Hi. Some of the things you pointed out are very relevant and hence i've modified the script now. Note that this is not a module , its a package. I would like to keep the dimension of my script the way it is.
    Packagtest.pl
    package Packagetest; BEGIN{ print"You are using Packagetest\n"; } sub ReadFile { use strict; use warnings; my ($fn) = @_; open(my $fh, '<', $fn) || die "cannot read the file: $!"; while (<$fh>) { chomp; my @tokens = split /\|/; print "Wrestlername: $tokens[0]\n"; print "Crowdreaction: $tokens[1]\n"; print "Specialmove: $tokens[2]\n\n"; } } return 1; END{ print"Thank you for using the package\n"; }
    Here is the script that calls this package
    TestPackage.pl
    #!/usr/bin/perl -w use strict; use warnings; require 'Packagetest.pl'; Packagetest::ReadFile("datafile");

      What do you mean by package? There are scripts, modules and distributions. You used require, so it better be a module. If it's not a module, it doesn't make sense to use require or use. It's a bug.

      Why did you revert the extension change? It confuses your readers and maintainers. It also forces you to use require instead of use. Not only is that really unusual, it serves no benefit and it causes a number of issues.

      Why did you remove the file name from the message? It would have solved your original problem if the error message had included the file name. It helps elsewhere too.

      Why did you add the line number to the IO message (by removing the "\n"). If your program can't open the file because it wasn't found or because of a permission problem or for any other reason, the person reading the message has no need to know the error occurred at line 11 of your module to fix the problem.

      Why did you move use strict; and use warnings; into the sub, effectively turning them off for the rest of the module.

      Why did you move the output back into the reader? That makes no sense.