Perl (Scripting) - Open file for reading (<)

by
Jeremy Canfield |
Updated: September 09 2022
| Perl (Scripting) articles
There are two common approaches to opening a file in Perl. In this example, FH is the identifier that will be used to interact with example.txt.Technically, you do not have to use FH as the identifier . You could use any string, such as IN or OUT or WHATEVER.
It is not necessary to include the -e (exists) and -r (readable) flags but this is a good best practise, to ensure the file exists and is readable and can be opened.
my $file = "/path/to/example.txt";
if (-e $file and -r $file and open FH, "<", $file ) {
print "Successfully opened $file for reading \n";
close FH;
}
else {
print "$file does not exist, is not readable, or failed to be opened \n";
exit 1;
}
In this example, $fh is the variable that will be used to interact with example.txt.
my $file = "/path/to/example.txt";
if (-e $file and -r $file and open my $fh, "<", $file ) {
print "successfully opened $file \n";
close $fh;
}
else {
print "$file does not exist, is not readable, or failed to be opened \n";
exit 1;
}
In this example, the entire contents of the file will be store in a variable named $foo.
my $file = "/path/to/example.txt";
my $foo = "";
if (-e $file and -r $file and open FH, "<", $file ) {
while (my $line = <FH>) {
$foo .= $line;
}
chomp $foo;
close FH;
}
else {
print "$file does not exist, is not readable, or failed to be opened \n";
exit 1;
}
Following in an example of how to read a file using $fh.
my $file = "/path/to/example.txt";
if (-e $file and -r $file and open my $fh, "<", $file ) {
while (my $line = <$fh>) {
print $line;
}
close $fh;
}
else {
print "$file does not exist, is not readable, or failed to be opened \n";
exit 1;
}
Did you find this article helpful?
If so, consider buying me a coffee over at