
Pattern matching (searching for text) is something most programmers have to do, and the choice of Perl as the language to do it is an excellent choice.
It may help to break down the task into some logical sections.
You can search by pattern or condition or both.
You may wonder what kind of condition you might look for if all you want is to find 'abc' in some text.
Well, you may want to see if it is at the beginning of a line (string) or at the end. For example, if you are looking for all files ending in '.pl' in a huge list of files, you would want to restrict your search to the end of the string - that's the condition.
The pattern is '.pl'.
You might try something like this:
@files = ("bac.pl.txt","backup3.sh","Bakup_full.app","Bakup-pico.app","Bakup.app",
"bakup.pl","bakup.sh","Bakup2.app","BakupOld.app","base10clock.sh","bash_profile.txt","bash-fix");
$pattern = ".pl";
foreach (@files) {
print "$_\n" if (m/$pattern/);
}
But that would also find the first file 'bac.pl.txt', which is not what we want.
![]()
We need to supply a condition to our expression - only look at the end of the string. Each element in the array is considered a separate string. To do that we use the $ metacharacter:
@files = ("bac.pl.txt","backup3.sh","Bakup_full.app","Bakup-pico.app","Bakup.app",
"bakup.pl","bakup.sh","Bakup2.app","BakupOld.app","base10clock.sh","bash_profile.txt","bash-fix");
$pattern = ".pl";
foreach(@files) {
print "$_\n" if (m/$pattern$/);
}
![]()
Note the position of the $ is at the end of our search pattern. To search at the beginning of the string, we would use the ^ caret metacharacter, at the beginning of the pattern:
@files = ("bac.pl.txt","backup3.sh","Bakup_full.app","Bakup-pico.app","Bakup.app",
bakup.pl","bakup.sh","Bakup2.app","BakupOld.app","base10clock.sh","bash_profile.txt","bash-fix");
$pattern = "B";
foreach(@files) {
print "$_\n" if (m/^$pattern/);
}

So, in these examples, we searched for a pattern AND a condition.