in reply to substring within range
This sound like a home work, you should show us what did you try before
I hope you can understand next code, which do what do you want. See split,perlre, and substr if you need help reading it.Updated: For fun,see this example for use regex "...(..)..(..).." style (no substr needed). For "x" usage see Multiplicative Operators:#!/usr/bin/perl use strict; use warnings; my $range="0-2,6-10,13,15"; my $test="this is a test with more than 15 characters"; for my $r (split (",",$range)) { if ($r =~ /^(\d+)(-(\d+))?$/) { my $first=$1; my $length=1; if (defined ($3)) { $length=$3-$1+1; } print "$r - ", substr ($test, $first,$length),"\n"; } }
#!/usr/bin/perl use strict; use warnings; my $range="0-2,6-10,13,15"; my @range=split(",",$range); my $test="this is a test with more than 15 characters"; my $last=0; my $regex=""; for (@range) { if (/^(\d+)(-(\d+))?$/) { my $first=$1; my $length=1; if ($last lt $first) { $regex.="."x($last-$first); } $last=$first; if (defined ($3)) { $length=$3-$1+1; $last=$3; } $regex.="(".("."x$length).")"; } } my @matches = $test =~ /$regex/; my $n=0; for (@matches) { print ++$n." ($range[$n-1]): \"" ."$_","\"\n"; }
|
|---|