Beefy Boxes and Bandwidth Generously Provided by pair Networks
P is for Practical
 
PerlMonks  

file handles and file input

by PerlZealot (Acolyte)
on Feb 12, 2008 at 20:25 UTC ( [id://667666]=perlquestion: print w/replies, xml ) Need Help??

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

I am currently playing around with a Perl script which is supposed to read lines of text from files, chomp, then chop them, and then print the output to an output file. Only problem is, is that the script is starting at the second line in the (input) text file, and skipping every other line. Here is the code...
#!/usr/bin/perl my $filestring = $ARGV[0]; my $outfile_str = "$ARGV[1]"."_new"; open(IN, "<$filestring"); open(OUT, ">$outfile_str"); my $string_parser; while(<IN>){ $string_parser = <IN>; print "$string_parser"; chomp $string_parser; chop $string_parser; print OUT "$string_parser "; } close(IN); close(OUT); Any ideas?

Replies are listed 'Best First'.
Re: file handles and file input
by kyle (Abbot) on Feb 12, 2008 at 20:35 UTC

    The problem is that while(<IN>) reads a line of the file (and puts it into $_), and $string_parser=<IN> also reads a line from the file. Try this instead:

    while ( $string_parser = <IN> ) { print "$string_parser"; # ... }
Re: file handles and file input
by pc88mxer (Vicar) on Feb 12, 2008 at 20:38 UTC
    The while (<IN>) is reading a line from the file (and placing the result in $_) and then you are reading yet another line with

    $string_parser = <IN>;

    So that's why $string_parser is being set to every other line.

Re: file handles and file input
by GrandFather (Saint) on Feb 12, 2008 at 20:38 UTC

    Try:

    while(my $string_parser = <IN>) {

    instead of while(<IN>) which reads a line into $_, then $string_parser = <IN> which reads the next line into $string_parser - effectively throwing away the previous line.


    Perl is environmentally friendly - it saves trees
Re: file handles and file input
by sh1tn (Priest) on Feb 12, 2008 at 21:35 UTC
    Use perldoc -q when in doubt. perldoc -q file and perldoc -f readline in this case.


        Unless I prefer cli pod access to http one.
        Otherwise nice point.
Re: file handles and file input
by Anonymous Monk on Feb 12, 2008 at 21:18 UTC
    Oops!!! Sorry about that!!!

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://667666]
Approved by leocharre
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others surveying the Monastery: (3)
As of 2024-03-29 06:54 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found