"Perl for Perl Newbies" - Part 2Regular ExpressionsUseful Flags

7.8. Useful Flags

There are other flags than e that can be appended to the end of the match or substitution.

An i following the regular expression call, causes a case-insensitive operation on the string. Thus, for example, an "A" will match both "a" and "A". Note that the strings placed in $1, $2 and friends will still retain their original case.

A g causes the match or substitution to match all occurrences, not just one. If used with a match in an array context (e.g: @occurrences = ($string =~ /$regexp/g);) it retrieves all the matches and if used with a substitution it substitutes all the occurrences with the string.

This example replaces all the occurrences of the word "hello" by the index of their occurrence:

use strict;
use warnings;

my $index = 0;
sub put_index
    return $index;

my $string = shift;

$string =~ s/hello/put_index()/gei;

print $string, "\n";

Written by Shlomi Fish