Perl read/write File

This is a simple example how to write into a File with Perl, and then read from it.At first we write the numbers from 1 to 6 into the file, in the second we read from the file and print it on the screen, if you don’t want the “\n” at the end use the function chomp.

If you open a File for read use ‘<‘, for write ‘>’ and for append ‘>>’.

#!/usr/bin/perl
use warnings;
use strict;

#declare filehandler
my ($fh_read,$fh_write);


#open file for write
open($fh_write, ">", './testfile') or die "Failed to open file: $!\n";

#now write
for my $num (1..6){
	print $fh_write "$num\n";
}

#close the file
close($fh_write);


#open file for read
open($fh_read, "<", './testfile') or die "Failed to open file: $!\n";

#now read
while (my $row = <$fh_read>) {
  print $row;
}

#close the file
close($fh_read);

Result looks like:

1
2
3
4
5
6

you could check if a handler is open with this Perl handler function.

2 thoughts on “Perl read/write File”

Leave a Reply

Your email address will not be published.

three × 1 =