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

I am using the following subroutine with strict in order to read a supplied file and return it's contents in an array. I am getting errors saying I cannot use the words passed to the function as Barewords, when I quote them, the program returns nothing, even though the file exists. Subroutine:
sub ReadFile { #Declare Variables # my ($game, $file) = @_; my $dir = "$ENV{HOME}/settings/$game/$file"; #End if dir not exist # return unless -d $dir; #Read the file and create the array # open(FILE, $dir)||die("Cannot open file : $!"); my @contents = <FILE>; close(FILE); #Cut trailing \n # chomp (@contents); #Return the array # return @contents; }
Program that calls on the sub
#!/usr/bin/perl5 use strict; use warnings; use HLDS; my @games = HLDS::ReadFile(HL1, HL1.txt); foreach my $game (@games) { print "$game\n"; }
Here are the Errors when I don't quote the strings...
Bareword "HL1" not allowed while "strict subs" in use at ./games.pl li +ne 8. Bareword "HL1" not allowed while "strict subs" in use at ./games.pl li +ne 8. Bareword "txt" not allowed while "strict subs" in use at ./games.pl li +ne 8. Execution of ./games.pl aborted due to compilation errors (#1) Uncaught exception from user code: Bareword "HL1" not allowed while "strict subs" in use at ./gam +es.pl line 8. Bareword "HL1" not allowed while "strict subs" in use at ./games.pl li +ne 8. Bareword "txt" not allowed while "strict subs" in use at ./games.pl li +ne 8. Execution of ./games.pl aborted due to compilation errors.
Any thoughts...

Replies are listed 'Best First'.
Re: sub strict refs errors.
by cephas (Pilgrim) on Oct 03, 2006 at 00:33 UTC
    return unless -d $dir;

    You are checking to see if $dir is a directory, even though you assigned a file to that variable just above it. Presumably HL1.txt is a file, so -d will return false.
Re: sub strict refs errors.
by grep (Monsignor) on Oct 03, 2006 at 00:34 UTC
    It's doing exactly what you told it to do.
    return unless -d $dir;
    It returns undef if your file is not a directory. I'm assuming H1.txt is a file.

    You might want to read about File test operators



    grep
    Mynd you, mønk bites Kan be pretti nasti...
Re: sub strict refs errors.
by GrandFather (Saint) on Oct 03, 2006 at 00:39 UTC

    What are HL1, HL1 and txt and why are you concatenating the last two?

    What Perl sees are three bare words and assumes they are subroutine calls (HL1, HL1 and txt). The . is the concatenation operator. Perhaps what you meant was:

    my @games = HLDS::ReadFile ('HL1', 'HL1.txt');

    Update: Doh, /me slaps self about the head with a wet fish having read the fine print in the OP.


    DWIM is Perl's answer to Gödel
      Argh, That was a really stupid mistake on my part there with the test operator...Sorry about that guys, thanks for the fast replies. I'll quote the individual parameters and see if it returns right. Thanks.