Beruflich Dokumente
Kultur Dokumente
FALL 2010
PROJECT – I
DATE: 10/20/2010
Write a perl program to copy the content of “gpa.txt” into another new text file called
“gpa_copy.txt”.
In addition, on the screen, print out the rows of “gpa.txt” which includes 4.0 GPA.
# gpa.txt
Name GPA
Asd 4.0
Sdf 3.2
Fghsd 3.6
Qwer 4.0
Program Code:
#!user/local/bin/perl
#$s=shift @ARGV;
$s="gpa.txt";
#$d=shift @ARGV;
$d="gpa_copy.txt";
open(KK,$s);
@lines=<KK>;
#print @lines;
print "\n\n";
open(IN,'<',$s) or die "cant read source file\n";
open(OUT,'>',$d) or die "cant read dest file\n";
while(<IN>)
{
print OUT;
}
close (IN);
close (OUT);
sub patt
{
foreach (@lines)
{ print "$_\n" if /$pattern/;
}
#print "\n";
}
$pattern= '[4]';
&patt;
close (KK);
Output:
Asd 4.0
Qwer 4.0
Result:
The required result was copied in the file “gpa_copy.txt” and was displayed in the output.
PART 2
Use the following regular expression for pattern matching, show the results and give a short
discussion
of the functionality of the regular expression from (1) to (9)
sub print_array
{ for ($i=0; $i<=$#strings;$i++)
{print $strings[$i], "\n";
}
print "\n\n";
}
sub grep_pattern
{ foreach (@strings)
{print "$_\n" if /$pattern/;
}
print "\n\n";
}
### Setting up the Array of strings
@strings = ("eee, 2, 7, four", "Perl is great", "1, Three", "Five, 7",
"This is exercise in Perl");
(1). $pattern = '\d';
(2). $pattern = '\d+.+';
(3). $pattern = '\d+$';
(4). $pattern = 'e+'
(5). $pattern = 'e*'
(6). $pattern = 'e?'
(7). $pattern = '\bis\b'
(8). $pattern = '\b \w{4} \b'
(9). $pattern = '^[A-Z] '
Program Code:
#!usr/local/bin/perl
@strings=("eee, 2, 7, four", "Perl is great", "1, Three", "Five, 7", "This is exercise in Perl");
sub print_array
{
print "\n\n";
for ($i=0; $i<=$#strings; $i++)
{ print $strings[$i], "\n";
}
print "\n\n";
}
sub grep_pattern
{
foreach (@strings)
{ print "$_\n" if /$pattern/;
}
print "\n\n";
}
&print_array;
$pattern = '[2]';
&grep_pattern;
Output:
eee, 2, 7, four
1, Three
Five, 7
2. $pattern = '\d+.+';
eee, 2, 7, four
1, Three
Displays lines starting with any character and ending with digits
Five, 7
eee, 2, 7, four
Perl is great
1, Three
Five, 7
This is exercise in Perl
eee, 2, 7, four
Perl is great
1, Three
Five, 7
This is exercise in Perl
Perl is great
Perl is great
Five, 7
This is exercise in Perl