in reply to Re: Specific instance of a repeated string
in thread Specific instance of a repeated string

Wow, it's 03:45, so I'm going to have to tickle the back of my throat and spew what I've got so far.   Besides the comments and debug stuff there's really only 8-10 lines of real code in the loop that does the good stuff.   Anyway, pardon the mess, it's an inspiration still steaming from the source...

The idea I had was getting an RE to create an array of string pieces, alternating number and non-number chunks.   If you could then figure out the array index of the requested number chunk you'd operate on that.   And then collapse the pieces back together into the updated filename string when needed.

my $nbridx = 1; my $filename; while( $filename = <DATA> ) { next if $filename =~ m/^\s*#/; chomp( $filename ); # First split filename into alternating non-numeric and numeri +c # chunks. Any defined string will match here. my @a = $filename =~ m/ (\D+)? (\d+)? /xg; # The m//g always tries once too many, so throw away the last # two <undef> array elements. splice(@a,-2,2); # An empty string would result in an empty array. next unless @a; # Leading/embedded/trailing spaces are not dealt with here. # Now we have an array where numeric chunks are at odd-numbere +d # indexes and non-numeric chunks are at even-numbered indexes. # Note that the leading and/or trailing elements may be undef. # Examples: # 'number.', '9' # '<undef>', '1', '.cgi', '<undef>' # 'bottles', '99', '.ale', '<undef>' # printf "I split into '%s'\n", join("', '", doud(@a) ); # Figure out how many number chunks exist in this array then # check against how many are needed. my $nbrcnt = int( scalar(@a) / 2 ); $nbrcnt-- unless defined $a[-1]; if( $nbridx == 0 or abs($nbridx) > $nbrcnt ) { printf "This filename only has %d number chunks and you as +ked for the %d'th one!\n", $nbrcnt, $nbridx; next; } # Now a little math to figure out the array index of wanted nu +mber my $chkidx = ($nbridx>0) ? ( $nbridx * 2 - 1 ) : ( ($nbridx + $nbrcnt) * 2 + 1 ); # printf " Desired index %d Number Chunks %d Internal ind +ex %d\n", # $nbridx, $nbrcnt, $chkidx; # All the actual manipulation of $a[$chkidx] would be the # next little bit (cough) to implement here # Show the chunk we operated on and rebuild the string. $filename = join( '', grep { defined $_ } @a ); printf " Using '%s' from '%s'\n", $a[$chkidx], $filename; } sub doud { map { defined($_) ? $_ : '<undef>' } @_ }; __END__ wrong_number! 01-file02.html 11-file22tom33bill.html 1.cgi number.9 bottles99.ale 0bottles.beer 666
This is a lot just to show an idea, but you might've not seen an RE do something like this before ...
my @a = $filename =~ m/ (\D+)? (\d+)? /xg;

Replies are listed 'Best First'.
Re^3: Specific instance of a repeated string
by Ionizor (Pilgrim) on Aug 13, 2003 at 02:19 UTC

    Some excellent inspiration. Thank you.

    --
    Grant me the wisdom to shut my mouth when I don't know what I'm talking about.