How to work with file files in Perl

Home > Search > How-to
  by

Display file content

$file = "/path/to/file.txt";
open(FH, '<', $file) or die "cannot open $file";

while (<FH>) {
  print $_;
}

close(FH);

 


Display lines that contain a certain string

Let's say file.txt has numerous lines of text.

Hello World
Goodbye Earth
How are you

 

The following script will only print lines that contain the text "Hello".

$file = "/path/to/file.txt";
open(FH, '<', $file) or die "cannot open $file";

while (<FH>) {
  if ($_ =~ /Hello/) {
  print $_;
  }
}

close(FH);

 

Often, you will want to create a new variable that contains a certain string from the file.

$file = "/path/to/file.txt";
open(FH, '<', $file) or die "cannot open $file";

while (<FH>) {
  if ($_ =~ /Hello/) {
  $Greeting = $_;
  }
}

close(FH);

print $Greeting;

 


Writing text to a file

The following markup is used to redirect the text Hello World to file.txt. A single > is used, meaning that the entire file will be overwritten with the text Hello World.

$file = "/path/to/file.txt";
open(FH, '>', $file) or die "cannot open $file";
select(FH);
print "Hello World";
close(FH);

 


Sum of whole numbers in a file

Let's say file1.txt contains whole numbers.

5
-10
15.4
20

 

The following markup will get the sum of the whole numbers in file1.txt. Running this will script will produce 30.4, which is the sum.

$sum = 0;
$file = "/path/to/file.txt";

open(FH, '<', $file) or die "cannot open $file";

while (my $line = <FH>) {
  sum += $line;
}

print "$sum\n";
close(FH);

 


Replace text in a file

Let's say file.txt contains the text "Hello World". The following Perl script will open file.txt, and then replace the text "World" with "Earth".

open(FH, '<', '/path/to/file.txt') or die "cannot open file";
my @lines = <FH>;
close(FH);

my @newlines;
foreach(@lines) {
  $_ =~ s/World/Earth/g;
  push(@newlines,$_);
}

open(FH, '>', '/path/to/file.txt') or die "cannot open file";
print FH @newlines;
close(FH);

 



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 in the box below so that we can be sure you are a human.




Comments