On Wed, Jun 9, 2010 at 22:17, Peng Yu <[email protected]> wrote:
> I can't find an existing perl subroutine (in the library) to find
> every occurrence of a substring in a string. The following webpage
> "Example 3b. How to find every occurrence" uses a loop to do so. But
> I'd prefer a subroutine. Could you let me know if such a subroutine is
> available in perl library?
>
> http://perlmeme.org/howtos/perlfunc/index_function.html
snip
So long as the number of times "abab" occurs in "abababab" is twice,
not three times (i.e. you do not allow overlaps), you can just say
my $count =()= $string =~ /abab/g;
or, if you need to use it in a function call, you can say
somefunction( "first_arg", scalar ()= $string =~ /abab/g, "third_arg" );
These work because the regular expression /abab/g will match the
string "abab" as many (non-overlapping) times as it can. In list
context a regular expression will return the matches it made, so
my @a = "ababababababab" =~ /abab/;
will assign ("abab", "abab", "abab") to @a (note that the extra "ab"
is ignored). The list assignment operator returns the number of items
on its right hand side when in scalar context, so
my $count = my @a = "ababababababab" =~ /abab/;
will assign 3 to $count. You can replace "my @a" with "()" and get
the same effect because the list assignment operator returns the
number of items on its right hand side (not the number of elements
assigned):
my $count = () = "ababababababab" =~ /abab/;
This idiom is used fairly often, and the convention is to remove the
spaces between the assignment operators and the empty list to produce
the "secret operator" =()=.
You may find the following resources helpful:
A quick reference guide for operators:
http://github.com/cowens/perlopquick/blob/master/perlopquick.pod
The reference for operators:
http://perldoc.perl.org/perlop.html
The regular expression tutorial
http://perldoc.perl.org/perlretut.html
The reference for regular expressions:
http://perldoc.perl.org/perlre.html
The quick reference for regular expressions
http://perldoc.perl.org/perlrequick.html
The last four are also available on your machine from the perldoc command:
perldoc perlop
perldoc perlretut
perldoc perlre
perldoc perlrequick
--
Chas. Owens
wonkden.net
The most important skill a programmer can have is the ability to read.
--
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]
http://learn.perl.org/