Beefy Boxes and Bandwidth Generously Provided by pair Networks
We don't bite newbies here... much
 
PerlMonks  

Re: substring within range

by i5513 (Pilgrim)
on Feb 04, 2015 at 09:43 UTC ( [id://1115497]=note: print w/replies, xml ) Need Help??


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.
#!/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"; } }
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 @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"; }

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://1115497]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others drinking their drinks and smoking their pipes about the Monastery: (2)
As of 2024-04-19 18:54 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found