[sf-perl] Plucking from a string

Fred Moyer fred at redhotpenguin.com
Thu May 22 15:25:38 PDT 2008


Neil Heller wrote:
> I just wrote the code below and was wondering how I could make a inner 
> loop A LOT simpler.
> 
> I would appreciate any suggestions.

I was able to do it with a regex and a map statement - is this what you 
wanted?  I hacked it out in the perl debugger.

phred at pooky ~ $ perl -d -e 0

Loading DB routines from perl5db.pl version 1.28
Editor support available.

Enter h or `h h' for help, or `man perldebug' for more help.

main::(-e:1):   0
 
                 DB<1> $string = 'vvvbcd=7wwwbcd=88xxxbcd=999yyybcd=1000zzz'
 
               DB<2> x $foo = 'bcd='
0  'bcd='

DB<3> x @foos = map { $foo . $_ } $string =~ m/$foo(\d+)/g

0  'bcd=7'
1  'bcd=88'
2  'bcd=999'
3  'bcd=1000'


> 
> Basically the code works like this:
> 
> Given an arbitrary string, that string contains a single identifier (in 
> this case “bcd=”) followed by a numeric value.
> 
> I would like to pull out the identifier and the value so the resulting 
> display is (for example):
> 
> bcd=7
> 
> bcd=88
> 
> bcd=999
> 
> bcd=1000
> 
>  
> 
> Neil Heller
> 
>  
> 
>  
> 
> #! usr/bin/perl
> 
>  
> 
> use warnings;
> 
> use strict;
> 
>  
> 
> my $counter = 0;
> 
> my $theline = "vvvbcd=7wwwbcd=88xxxbcd=999yyybcd=1000zzz";
> 
> my $TARGETSTR = "bcd=";
> 
> my $spot = 0;
> 
> my $done = 0;
> 
> my $fragment;
> 
> my ($inner_done, $inner_char, $inner_count);
> 
> my $NUMERIC = "0123456789";
> 
>  
> 
> while (!$done) {
> 
>     $spot = index $theline, $TARGETSTR;
> 
>     if ($spot == -1) {
> 
>         $done = 1;
> 
>     } else {
> 
>         $fragment = substr $theline, $spot;
> 
>         print $TARGETSTR;
> 
>         $inner_done = 0;
> 
>         $inner_count = 4;
> 
>         while (!$inner_done) {
> 
>             $inner_char = substr $fragment, $inner_count, 1;
> 
>             if ((index $NUMERIC, $inner_char) > -1) {
> 
>                 print $inner_char;
> 
>                 $inner_count++;
> 
>             } else {
> 
>                 $inner_done = 1;
> 
>             }
> 
>         }
> 
>         print "\n";
> 
>         $fragment = substr $fragment, 5;
> 
>         $theline = $fragment;
> 
>     }
> 
> }
> 
> 
> ------------------------------------------------------------------------
> 
> _______________________________________________
> SanFrancisco-pm mailing list
> SanFrancisco-pm at pm.org
> http://mail.pm.org/mailman/listinfo/sanfrancisco-pm


-- 
Red Hot Penguin Consulting LLC
mod_perl/PostgreSQL consulting and implementation
http://www.redhotpenguin.com/


More information about the SanFrancisco-pm mailing list