Perl_Series I

Assume the file contains 10 words and we need to find the longest word and print on the console with help of perl script. Following are different ways to open a file and read the content using perl

  • less than < sign indicates that file has to be opend in read-only mode.
    open(DATA, “<vlsispace.txt”)
  • greater than > sign indicates that file has to be opend in the writing mode.
    open(DATA, “>vlsispace.txt”)
  • To open a file for updating without truncating it 
    open(DATA, “+<vlsispace.txt”)
  • To truncate the file first 
    open DATA, “+>vlsispace.txt”
  • In this mode, writing point will be set to the end of the file and append new data to file
    open(DATA,”>>vlsispace.txt”)
  • To read the data in a file during append process
    open(DATA,”+>>vlsispace.txt”)

#!usr/bin/perl
open r,”<data.txt” or “cannot open the file”;
@string_words;
while($a=<r>)
{
chomp($a);
$i++;
@string_words[$i]=$a;
}
foreach $d(@string_words)
{
$i=length($d);
if($max<$i)
{
$word=$d;
$max=$i;
}
}
print “@string_words\n”;
print “the longest word:$word\n”;
print “the length of the longest word:$max\n”;
close r;

Comments