Beefy Boxes and Bandwidth Generously Provided by pair Networks
There's more than one way to do things
 
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
Replies are listed 'Best First'.
Re^3: Looking for pointers or optimizations.
by choroba (Canon) 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 imbibing at the Monastery: (15)
As of 2015-07-30 14:42 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The top three priorities of my open tasks are (in descending order of likelihood to be worked on) ...









    Results (271 votes), past polls