Tuesday, February 16, 2010

Perl interview questions Part #5

1) How to open and read data files with Perl?

Answer:

#!/usr/local/bin/perl

print ("Word to search for: $ARGV[0]\n");
$filecount =1;
$totalwordcount = 0;

while($filecount <= @ARGV-1) { unless (open (INFILE, $ARGV[$filecount]\n"); die ("Can't open input file $ARGV[$filecount]\n"); } $wordcount =0; while($line=) {
chop($line);
@words = split(/ /, $line);
$w =1;
while ($w<=@words) {
if ($words[$w-1] eq $ARGV[0]) {
$wordcount +=1;
}
}
print ("occurrences in file $ARGV[$filecount]: ");
print ("$wordcount\n");
$filecount ++;
$totalwordcount +=$wordcount;
}
print ("total number of occurrences: $totalwordcount\n");


Command line:
$perl program ERROR log1 log2
Word to search for: ERROR
occurrences in file log1: 1
occurrences in file log2: 0
total number of occurrences: 1


2) How do I do fill_in_the_blank for each file in a directory?

Answer:

# print out a list of files in the current directory

#!/usr/perl -w
opendir(DIR, ".");
@file=readdir(DIR);
closedir(DIR);

foreach $file(@files) {print "$file\n");
}

No comments:

Post a Comment

Search This Blog