Page 1 of 1

Perl File IO Manipulating files in Perl is easy! Rate Topic: -----

#1 jumptrooper  Icon User is offline

  • D.I.C Head
  • member icon

Reputation: 68
  • View blog
  • Posts: 234
  • Joined: 19-August 10

Posted 11 September 2010 - 10:06 PM

Perl File IO

In order to interact with a file, Perl makes you specify a thing called a "filehandle". This is basically a variable but, of course, Perl has a special way of talking about variables that reference files.

Normal variables in Perl typically begin with a symbol, such as $, @, or %. Filehandles, by convention, are specified in all caps, like this: MYINFILE, and have no type of symbol preceding them.

You can open files for reading, writing/creating/truncating, and appending.

To open a file for reading you would type:
open(FILEHANDLE, "/name/o/me/file.here");

## or you could use
open(FILEHANDLE, "<infile.txt");  # the "<" means "read-only mode"



And that's it - your file is now open for reading.

If you wanted to open a file for writing you would use:
open(MYWRITEFILE, ">out.txt"); 
# the ">" makes the file open for writing/creating and truncates 
# (erases) the existing contents before any writting takes place.



There are several "modes" you can open a file in:
< Reads only
> Creates, writes and truncates
>> Writes, appends and creates
+< Reads and writes
+> Reads, writes, creates and trucates
+>> Reads, writes, appends and creates

Appending to a file opens the file and places the file pointer at the very end of the file. When you begin writing to the file everything gets added to the end of the existing content.

Any time you open a file, you must also close it when you are finished. To close a file you use:
close(FILEHANDLENAME);



Once a file is open for reading you can parse through it line by line like so:
...
while(<FILEHAND>){
  # do stuff here
}
...



To print to a file you could use the following syntax:
print FILEHANDLE "the stuff I want to print and the contents of this variable";
print FILEHANDLE "$myVariable";



Here is a small sample program that reads in the contents of a file, modifies them and writes them back out to a new file. It will also append a note to a log file recording the modification. Finally, it closes the files and exits. If you want to try it, just create a text file named "in.txt" in the same directory as the program and fill it with some text.
#!/usr/bin/perl -w 
use strict;

open(READFILE, "in.txt") or die print "Can't open the read file: $!\n";
open(WRITEFILE, ">out.txt") or die print "Can't open the write file: $!\n";

while(<READFILE>){
  my $line = $_;  # store the contents of the line in $line
  $line = uc($line); # convert everything to uppercase
  print WRITEFILE "$line"; # write the converted contents to out.txt
}

open(LOGFILE, ">>log.txt");
my $time = time();
print LOGFILE "Just wrote all caps to out.txt at $time\n";

close(READFILE);
close(WRITEFILE);
close(LOGFILE);



If you'll notice, we use the "die" command when we opened the files for interaction. "die" halts the programs execution when perl fails to open the file for whatever reason. You can optionally tell it to do stuff after it dies, such as print a message. In the previous example, "$!" prints the error message that normally would appear on the command prompt.
If you don't want to halt the program, you can use the "warn" command instead of "die", which will allow you to print a message stating that the open failed, but will let the program proceed with execution.

And that's a sample of file IO in Perl.

Is This A Good Question/Topic? 0
  • +

Replies To: Perl File IO

#2 chorny_cpan  Icon User is offline

  • D.I.C Head
  • member icon

Reputation: 2
  • View blog
  • Posts: 52
  • Joined: 13-May 09

Posted 26 November 2010 - 02:14 PM

This tutorial is outdated - you should use lexical filehandles and 3-arg open.
Was This Post Helpful? 2
  • +
  • -

#3 jumptrooper  Icon User is offline

  • D.I.C Head
  • member icon

Reputation: 68
  • View blog
  • Posts: 234
  • Joined: 19-August 10

Posted 03 December 2010 - 12:45 PM

View Postchorny_cpan, on 26 November 2010 - 01:14 PM, said:

This tutorial is outdated - you should use lexical filehandles and 3-arg open.


Oooo! Yay! Actual feedback!
Thanks for pointing this out. My reference manuals are a bit old so it's good that you're steering me towards techniques in line with the Perl communities agreed upon best practices.
I found an article on stackoverflow.com re: lexical filehandles and 3-arg open here and it does a good job of explaining why what you say is true.
Apparently open(OUT, '>>', $file); is what you've referred to as the 3-arg open and using a standard variable for the file name is "lexical filehandle" part of it.
So if we want to open files "properly", we should do it like this:
open (my $foo, '<', ' abc');

Is this right?

On Stackexchange, one replay gave this as reasons:

Quote

* Using typeglobs for filehandles (like OUT) is not a good idea, as they are global across your entire program - you need to be sure that no other routine including those in modules are using the same name (including in the future).
* Using the two-argument form of open exposes your application to mis-behaviour caused by variables containing special characters, for example my $f; open $f, ">$some_filename"; is exposed to the bug where $some_filename containing a leading > will change the program's behaviour.

Using the three-argument form avoids this by separating the mode and filename into separate arguments where they can't interfere.

Was This Post Helpful? 0
  • +
  • -

#4 vigoloubev  Icon User is offline

  • New D.I.C Head

Reputation: 3
  • View blog
  • Posts: 16
  • Joined: 17-February 11

Posted 22 February 2011 - 03:07 AM

I prefer to use IO::File, IO::*
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1