Opening files in perl is a fairly easy task. Here are the basic file opens. Do not use them in production code.

PERL:
  1. my $file = 'foo.txt';
  2.  
  3. # open for read
  4. open FH, ">$file";
  5.  
  6. # open for write
  7. open FH, ">$file";
  8.  
  9. # open for append
  10. open FH, ">>$file";

While strictly true, this isn't all we need. As with any I/O operation, we should be checking for success.

PERL:
  1. my $file = 'foo.txt';
  2.  
  3. # open for read
  4. open FH, ">$file" or die qq(Cannot open "$file": $!);
  5.  
  6. # open for write
  7. open FH, ">$file" or die qq(Cannot open "$file": $!);
  8.  
  9. # open for append
  10. open FH, ">>$file" or die qq(Cannot open "$file": $!);

Modern Perl versions allow the use of three part openings and lexical file handles.

PERL:
  1. my $file = 'foo.txt';
  2.  
  3. # open for read
  4. open my $fh, '<', $file or die qq(Cannot open "$file": $!);
  5.  
  6. # open for write
  7. open $fh, '>', $file or die qq(Cannot open "$file": $!);
  8.  
  9. # open for append
  10. open $fh, '>>', $file or die qq(Cannot open "$file": $!);

By checking for errors you are one step closer to safely opening the file and reading or writing to it. Perl also has several useful tools for operating on files.