On Jun 12, 7:40 pm, chas.ow...@gmail.com ("Chas. Owens") wrote:
> On Sat, Jun 12, 2010 at 22:18, Randal L. Schwartz <mer...@stonehenge.com> 
> wrote:>>>>>> "Peng" == Peng Yu <pengyu...@gmail.com> writes:
>
> > Peng> I can't find an existing perl subroutine (in the library) to find
> > Peng> every occurrence of a substring in a string. The following webpage
> > Peng> "Example 3b. How to find every occurrence" uses a loop to do so. But
> > Peng> I'd prefer a subroutine.
>
> > You had me up to here.  Why?  Why a *subroutine*?  That's like saying "I
> > really like variable names, but only if they start with a
> > consonant... not a vowel!"
>

Just for the record though, the OP's webpage citation indicates
the goal was finding the locations of the substring rather than
just the total substring count.

>
> Subroutines play nice with each other:
>
> do_x number_of_substrings_in_string $string, $substring;
>
> To use a regex you have to use an ugly hack:
>
> do_x scalar ()= /ab/g;
>
> or a useless temporary variable (with an ugly hack):
>
> my $count =()= /ab/g;
> do_x $count;
>

Of course, ugliness can be in the eye of the beholder.
To some the latter idiom you've shown may be as
appealing and elegant as a built-in with a potentially
hard-to-recall name or a tricky argument sequence.

Also, TIMTOWDI can come to the rescue often. The
alternative below may be just as  ugly but is arguably
less magical:

do_x   do{ $n++ while /ab/g; $n };

> ...

--
Charles DeRykus


--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/


Reply via email to