File contents – Perl

In this post I will list some methods related to file contents operation using Perl.

1. Count lines in a file

2. Trailing a growing file

3. Reading a particular line in a file

4. Delete the last line from a file

5. Compare the contents of two files

#! /usr/local/bin/perl
use IO::Handle;
use Tie::File;
use Fcntl;
use File:Compare;

##################################
# Count lines in a file
##################################
my $file = “test.txt”;
my $count = 0;

# Method 1
$count = `wc -l < $file`;
die “wc failed: $?” if $?;

chomp($count);
print “The number of lines in $file is $count \n”;

# Method 2
$count = 0;
open(FILE, “$file”) or die “can’t open $file: $!”;
$count++ while <FILE>;
print “The number of lines in $file is $count \n”;
close FILE;
##################################
# Trailing a Growing File
##################################
$file2 = “trailing.txt”;
open(FILE2, “$file2”) or die “can’t open $file2: $!”;
for (;;){
while(<FILE2>){
print “$_ . “;
}
sleep 10;
FILE2->clearerr();#It will clear the EOF flag
}
close FILE2;
##################################
# Reading a particular line in a file
##################################
#method 1
my $. = 0;
my $num = 20;
my $line = “”;
open(HANDLE, “$file”) or die “can’t open $file: $!”;
do {$line = <HANDLE>} until $. == $num || eof;
print “the line in $num is $line \n”;
close HANDLE;
#method 2
open(HANDLE, “$file”) or die “can’t open $file: $!”;
@lines = <HANDLE>;
$line = $lines[$num -1];
print “the line in $num is $line \n”;
close HANDLE;
#method 3
@lines = “”;
$line = “”;
tie(@lines, Tie::File, $file, mode=> 0_RDWR) or die “Cannot tie file $file : $! \n”;
$line = $lines[$num -1];

##################################
# Delete the last line from a file
##################################
delete $lines[-1];

##################################
# Compare the contents of two files
##################################
if (compare(“test.txt”,”test2.txt”) == 0){
print “They are equal \n”;
}

##################################
# Compare the contents with md5sum
##################################
$sum1 = `md5sum test.txt`;
$sum2 = `md5sum test2.txt`;
if ($sum1 == $sum2){
print “They are equal \n”;
}