Beefy Boxes and Bandwidth Generously Provided by pair Networks
Welcome to the Monastery
 
PerlMonks  

Re^3: File handling basics

by vinoth.ree (Monsignor)
on Jul 17, 2015 at 10:33 UTC ( [id://1135142]=note: print w/replies, xml ) Need Help??


in reply to Re^2: File handling basics
in thread File handling basics

If you are successfully opened the files, then your code,should be working.

open (F, $file) or die "cannot open file"; while (<F>){ print $_; } close F;

All is well. I learn by answering your questions...

Replies are listed 'Best First'.
Re^4: File handling basics
by ElectroRed (Initiate) on Jul 17, 2015 at 10:36 UTC
    Yeah. It's working. But  print $_; is printing whole text at a time. I want read every line. store it as an array and process.
      Yeah. It's working. But print $_; is printing whole text at a time.
      It is not exactly what it happening. In fact, the while loop reads one input line at a time and print $_; print each of these lines in turn. The difference is more important than you might think, as shown just below.

      I want read every line. store it as an array and process.
      Although you can do that, this is very rarely what you want to do. What you want to do, most of the time, is to read one line at a time with the while loop, process the line (e.g. make some changes to it and print the modified content, or extract some data for further calculation), and so on with the next line until the end of the file. The difference is that using a while loop is a lot more efficient that loading the whole file into an array if you don't need to, especially when the file is large

      Then replace the while loop with this code my @lines = <F>;

      open (F, $file) or die "cannot open file"; my @lines = <F>; close F;

      you can do the same with perl module File::Slurp

      use File::Slurp; my @array = read_file($filename);

      All is well. I learn by answering your questions...

      So what have you tried?

      Or did you confuse the Monastery with a Code-A-Matic machine?

      Downvoted the parent for lack of effort and a gimmé question.

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others romping around the Monastery: (5)
As of 2024-04-24 01:10 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found