[Ilugc] [TIP] perl tutorial V regex part 2

  • From: girishvenkatachalam@xxxxxxxxx (Girish Venkatachalam)
  • Date: Wed, 7 Dec 2011 08:44:50 +0530

There are many special variables in perl which can be seen with

$ perldoc perlvar

There are many for REGEX.

If you match a part of a string which is what you do all the time,

you can get the matched portion in the variable $&.

Example:

$str = "Here is a sample string";

if($str =~ /^Here/) {
           print $&;
}

It will print "Here".

Not useful?

It will be useful when you match using expressions.

The idiomatic and perl way of using regexes is when you read from a
file or stdin

We saw how to read from stdin using the diamond <> operator.

while(<>) {
      if(/\d+/) {
              print "I get digits $&\n";
      }
}

This will read any input from stdin and print out just the digits.

But only the first match. For all matches you have to use //g.

Anyway all matches are done on a line by line basis. So if you have a
regex that spans
 multiple lines you have to give one more switch to regex like //s or something.

Anyway you can easily write a cat(1) command in perl using:

$ cat cat.pl
#!/usr/bin/perl

while(<>) {
         print;
}

$ perl cat.pl /etc/passwd

will print the file on stdout.

-Girish
-- 
G3 Tech
Networking appliance company
web: http://g3tech.in ?mail: girish at g3tech.in

Other related posts:

  • » [Ilugc] [TIP] perl tutorial V regex part 2 - Girish Venkatachalam