On Sat, Jun 12, 2010 at 22:18, Randal L. Schwartz <[email protected]> wrote: >>>>>> "Peng" == Peng Yu <[email protected]> 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!" snip
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, you could wrap the hack up with your own subroutine. The next step is copying that subroutine to other programs. Now you have code duplication, so you look at making a module, but this is just one little function and hardly seems like it is worth the work. So, you throw a whole bunch of these little functions into one module called CompanyName::Utils. It is poorly organized, has next to no documentation, and has fifteen different versions of trim (each used by one or fewer programs). Or, you ask on the beginners list to see if someone has made a CPAN module that contains a function like the one you want. Personally, I would go with the temporary variable version because it better documents the what you want to happen and I can't be bothered with looking for a module for something I can do in one line of code, but I can completely understand the desire to avoid the mess going down the route of building you own function for such a trivial task. -- 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/
