FreeKB - Perl (Scripting) Read a file (<)
Perl (Scripting) - Read a file (<)

There are two common approaches to opening a file in Perl. In this example, FH is the string that will be used to interact with foo.txt.Technically, you do not have to use FH as the string. You could use any string, such as IN or OUT or WHATEVER.

if (open FH, "<", "foo.txt") {
  print "successfully opened foo.txt \n";
}
else {
  print "failed to open foo.txt \n";
  exit 1;
}

 

In this example, $fh is the string that will be used to interact with foo.txt.

if (open my $fh, "<", "foo.txt") {
  print "successfully opened foo.txt \n";
}
else {
  print "failed to open foo.txt \n";
  exit 1;
}

 

Following in an example of how to read a file using FH. This will display every line in foo.txt.

my $file = "foo.txt";

if (open FH, "<", $file) {
  while (my $line = <FH>) {
    print $line;
  }
  close FH;
}
else {
  print "failed to open $file \n";
  exit 1;
}

 

Following in an example of how to read a file using $fh.

my $file = "foo.txt";

if (open $fh, "<", $file) {
  while (my $line = <$fh>) {
    print $line;
  }
  close $fh;
}
else {
  print "failed to open $file \n";
  exit 1;
}

 



Add a Comment




We will never share your name or email with anyone. Enter your email if you would like to be notified when we respond to your comment.




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




Comments

Web design by yours truely - me, myself, and I   |   jeremy.canfield@freekb.net   |