Beefy Boxes and Bandwidth Generously Provided by pair Networks DiBona
No such thing as a small change
 
PerlMonks  

Re^2: Looking for pointers or optimizations.

by thmsdrew (Scribe)
on Aug 21, 2012 at 13:56 UTC ( #988742=note: print w/ replies, xml ) Need Help??


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, $_); }


Comment on Re^2: Looking for pointers or optimizations.
Download Code
Re^3: Looking for pointers or optimizations.
by choroba (Abbot) 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 (Priest) 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!!!

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://988742]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others examining the Monastery: (6)
As of 2014-04-18 02:14 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    April first is:







    Results (460 votes), past polls