http://www.perlmonks.org?node_id=988742


in reply to Re: Looking for pointers or optimizations.
in thread Looking for pointers or optimizations.

It worked fine but yes there was an empty file named 1.

If I change it to the following it should work as I meant it to:

open (my $fh, "<", $ARGV[0]) or die "Can't open input file!"; my @words; while (<>) { push(@words, $_); }

Replies are listed 'Best First'.
Re^3: Looking for pointers or optimizations.
by choroba (Cardinal) on Aug 21, 2012 at 14:00 UTC
    Better, but not yet correct: you should tell Perl which file handle to read from:
    while (<$fh>) {
    لսႽ† ᥲᥒ⚪⟊Ⴙᘓᖇ Ꮅᘓᖇ⎱ Ⴙᥲ𝇋ƙᘓᖇ
Re^3: Looking for pointers or optimizations.
by 2teez (Vicar) on Aug 21, 2012 at 14:05 UTC

    open (my $fh, "<", $ARGV[0]) or die "Can't open input file!"; my @words; ### The above die function should also return OS_ERROR if open funct +ion failed ### ... die "can't open file: $!"; while (<>) { ### <> will read from the STDIN not the filehandler $fh ### so that should be while(<$fh>){...} push(@words, $_); }

      So if I put in while (<$fh>) it breaks my my $guess = <> further down in my code. I made that my $guess = <STDIN> and it works fine.

        So if I put in while (<$fh>) it breaks my my $guess = <> further down in my code. I made that my $guess = <STDIN> and it works fine.

        both while(<>){..} and $guess = <> reads from STDIN. Atleast, that is obvious from your code. So, to make while(<fh>){.. work, you have to do this:

        my ($words_file) = @ARGV; open( my $fh, "<", $words_file ) or die "can't open file: $!"; my @words; while (<$fh>) { ... } ## later you use chomp(my $guess = <STDIN>); ...
        Please, pay attention to the DIRECTION of the "arrow"
        • ">" is 'Writing to' ( OUTPUT )
        • "<" is 'Read from' ( INPUT )
        NOTE: Like I mentioned previously, you didn't close the your filehandle!!!