First ...
Back ...
Next ...
Last ...
(Notes home)
Working with Patterns
|
Overview
- Perl's ability to work with patterns is extensive
- The =~ operator allows matching to be used
as an operator
- Built-in regular expression processing allows flexibility
in matching
- Built-in functionality from Unix programs such as
sed and tr allow familiar transformations
- split makes it easy to divide strings based
on patterns
- ... and much much more!
Code snippets
- Basic match syntax:
if ( $a =~ "hello" ) { .... }
- grep-like behavior:
print if ( /$var/ );
- tr-like behavior:
my $b =~ tr/$inpat/$outpat/
- sed-like substitution:
my $b; $b =~ s/$inpat/$outpat/i
(the i makes the match case insensitive)
Regular expressions
- Stuff to read:
man perlrequick ...
man perlre ...
man perlretut
- Detail: Perl doesn't necessarily distinguish between
a simple pattern and a regular expression. Also note that
patterns might be re-interpreted, even every time through a loop -
man perlretut for ways to avoid this.
- Sample: match letters @ start of line:
print if /^[a-zA-Z]/;
- Sample: splitting input based on whitespace
$x = "Calvin and Hobbes";
my @word = split /\s+/, $x; # $word[0] = 'Calvin'
# $word[1] = 'and'
# $word[2] = 'Hobbes'
|
First ...
Back ...
Next ...
Last ...
(Notes home)
UAF Computer Science
Prof. Greg Newby