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

Updated:   |  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 "failed to open $file due to the following: $! \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 "failed to open $file due to the following: $! \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 "failed to open $file due to the following: $! \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 "failed to open $file due to the following: $! \n";
  exit 1;
}

 




Did you find this article helpful?

If so, consider buying me a coffee over at Buy Me A Coffee



Comments


Add a Comment


Please enter ee97ae in the box below so that we can be sure you are a human.