Perl Open Not Reading All Lines of File

Perl File Handling: open up, read, write and shut files

This article describes the facilities provided for Perl file handling.

Opening files

Opening a file in perl in straightforward: open FILE, "filename.txt" or die $!; The command above will associate the FILE filehandle with the file filename.txt. You tin can use the filehandle to read from the file. If the file doesn't exist - or you cannot read it for any other reason - and so the script will die with the advisable fault message stored in the $! variable. What if you wanted to modify the file instead of just reading from it? Then you'd take to specify the appropriate way using the three-argument class of open. open FILEHANDLE, Style, EXPR The available modes are the following:
mode operand create truncate
read <
write >
append >>
Each of the to a higher place modes can also be prefixed with the + character to let for simultaneous reading and writing.
mode operand create truncate
read/write +<
read/write +>
read/suspend +>>
Notice, how both +< and +> open the file in read/write mode but the latter also creates the file if it doesn't be or truncates (deletes) an existing file. Then, if you wanted to open up a file for writing, creating it if information technology doesn't exist and truncating it kickoff if does, you lot'd practice the post-obit: open FILE, ">", "filename.txt" or die $! This functioning might fail if for example you don't have the appropriate permissions. In this instance $! volition exist set up appropriately. The mode and the filename in the 3-argument form can exist combined, so the above can likewise exist written as: open FILE, ">filename.txt" or die $!; As you might take guessed already if y'all just want read access you can skip the style just equally we did in the very first example above.

Reading files

If you want to read a text file line-by-line then you can exercise it equally such: my @lines = <FILE>; The <FILE> operator - where FILE is a previously opened filehandle - returns all the unread lines of the text file in list context or a unmarried line in scalar context. Hence, if you lot had a specially big file and you wanted to conserve memory you could procedure it line by line: while (<FILE>) { print $_; } The $_ variable is automatically ready for you lot to the contents of the current line. If you wish you may name your line variable instead: while (my $line = <FILE>) { ... will gear up the $line variable to the contents of the electric current line. The newline character at the terminate of the line is not removed automatically. If you wish to remove information technology y'all tin can utilize the chomp control. After all lines have been read the <FILE> operator will render a false value hence causing the loop to stop. There may cases where you need to read a file only a few characters at a fourth dimension instead of line-by-line. This may be the case for binary data. To do but that y'all can use the read control. open FILE, "motion-picture show.jpg" or die $!; binmode FILE; my ($buf, $data, $n); while (($due north = read FILE, $information, iv) != 0) { print "$north bytes read\n"; $buf .= $data; } close(FILE); There is a lot going on here so allow's have information technology step past step. In the offset line of the above code fragment a file is opened. As you tin can approximate from the filename it is a binary file. Binary files need to treated differently than text files on some operating systems (eg, Windows). The reason is that on these platforms a newline "character" is really represented within text files by the ii character sequence \cM\cJ (that's control-Grand, command-J). When reading the text file Perl volition convert the \cM\cJ sequence into a single \n newline characted. The antipodal also holds when writing files. Clearly, when reading binary data this behavior is undesired and calling binmode on the filehandle will make certain that this conversion is avoided. The read control takes either 3 or 4 arguments. The iii-argument grade is: read FILEHANDLE, SCALAR, LENGTH while the 4-argument form is: read FILEHANDLE, SCALAR, LENGTH, OFFSET In the first case LENGTH characters of data are read in the variable specified past SCALAR from FILEHANDLE. The return value of read is the number of characters actually read, 0 at the end of the file or undef in the example of an fault. Returning to our example to a higher place the third line of lawmaking will read at most iv characters of data into the $data variable. The number of characters read will be stored in $n. Successive read operations on the aforementioned filehandle volition fix the current file position to be merely earlier the start unread grapheme. Thus the code above volition read the contents of the file picture.jpg and store them in $buf, printing the number of characters read at every iteration. If Showtime is specified then the characters read will be placed at that position inside the SCALAR. Taking advantage of this we could rewrite the loop above equally such: my ($data, $due north, $kickoff); while (($north = read FILE, $data, 4, $offset) != 0) { print "$n bytes read\due north"; $first += $n; } Even though the example above demonstrates binary reading the read command works just equally well on text files - just make sure to use (for binary) or non apply (for text) binmode accordingly.

Writing files

Now that you know how to open up and read files learning how to write to them is straighforward. Take a look at the following lawmaking: open FILE, ">file.txt" or die $!; print FILE $str; close FILE; Not much is new hither. The only thing to detect is the two-statement use of print, the first argument being the FILEHANDLE to write to and the 2nd an expression to be written. The expression can be anything: a scalar, a list, a hash, etc. Appending to a file can be achieved in exactly the aforementioned way - apart from specifying the advisable (>>) mode of course. At this betoken you lot are probably thinking that a description of the write is what follows. Really, as the transmission page for write puts it:
Notation that write is not the opposite of read. Unfortunately.
Instead write is used to write formatted records to file, a subject outside the telescopic of this article.

Closing files

In one case y'all are done reading and writing you should close any open up filehandles. open FILE1, "file.txt" or dice $!; open FILE2, "flick.jpg" or die $!; ... shut FILE2; close FILE1; If you lot forget to close a filehandle Perl will practice it for you before your script exists simply information technology is expert practise to close yourself what yous have opened. The close command may also fail returning false, eg, if y'all try to close a closed filehandle. If yous want to grab these errors you can cheque the return value of close and the approriate fault message stored in $! as is done in the following example: close FILE or die $!

Summary of perl file handling

The open, close, print and read commands will allow yous to perform nearly common file operations. However, much more is possible. Apart from opening files you may open up pipes to other commands using the | manner and read from them or write to them using the techniques described. This and more than in an commodity to come.
Save This Page

Comments

[an mistake occurred while processing this directive]

Suggested Reading

Order your copy of Programming Perl now! Programming Perl covers all you demand to know about Perl file treatment.

[an error occurred while processing this directive]


uhligthereasione.blogspot.com

Source: http://www.perlfect.com/articles/perlfile.shtml

0 Response to "Perl Open Not Reading All Lines of File"

Publicar un comentario

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel