[Courses] [Perl] Part 5: The m// Operator
Karine Delvare
kproot at nerim.net
Mon May 2 02:52:10 EST 2005
On Fri, 29 Apr 2005 15:19:05 +0100
Dan <dan at cellectivity.com> wrote:
> LinuxChix Perl Course Part 5: The m// Operator
> 5) Exercises
>
> a) Write a program that reads /etc/passwd and outputs the line
> corresponding to your account.
#!/usr/bin/perl -w
use strict;
open MY_INPUT, "< /etc/passwd" or die "Couldn't open input file: $!";
while (defined(my $line = <MY_INPUT>))
{
if ($line =~ /^edhel:/)
{
print $line;
}
}
close MY_INPUT;
I wonder if there is a way to know when your regular expression is "enough". I started to search for /edhel/, then thought that would match zedhel or edhel2 if such users existed, so I tried /^edhel:/, but then I thought, what if it catches more than I want (like, if I had not thought about zedhel2). Do I have to be careful enough, or are there tips / techniques to get as accurate as possible with regexps ?
> b) Write a program that reads a C++ file and outputs all the #include
> statements. Assume that no include statement spans multiple lines,
> but consider that it might be indented.
#!/usr/bin/perl -w
use strict;
print "Please enter the path to a C++ file:\n";
my $file = <STDIN>;
open MY_INPUT, "< $file" or die "Couldn't open input file: $!";
while (defined(my $line = <MY_INPUT>))
{
if ($line =~ /\s*#include /)
{
print $line;
}
}
close MY_INPUT;
--
Karine Delvare
http://edhel.nerim.net/
More information about the Courses
mailing list