CGI/Perl Guide | Learning Center | Forums | Advertise | Login
Site Search: in

  Main Index MAIN
INDEX
Search Posts SEARCH
POSTS
Who's Online WHO'S
ONLINE
Log in LOG
IN

Home: Perl Programming Help: Beginner:
Help extracting from string with position number in file.

 



kaito
Novice

Oct 10, 2014, 11:18 PM

Post #1 of 2 (3574 views)
Help extracting from string with position number in file. Can't Post

Hey guys!

If i have a string like:


Code
$string="dogs are really awesome pets";


and I have a text file that points to starting position and ending positions of letters I need to extract. For example.

Here is what the text file will exactly contain.

Code
1-3,6-8,10-13


So I want 3 separate strings...

1st - dog
2nd- are
3rd - real

How do I tell my program to read those numbers? I think I can use the "substr" function to extract the letters. But how exactly do I tell my program to take those specific numbers in the text file?


(This post was edited by kaito on Oct 10, 2014, 11:25 PM)


Laurent_R
Veteran / Moderator

Oct 11, 2014, 3:30 AM

Post #2 of 2 (3565 views)
Re: [kaito] Help extracting from string with position number in file. [In reply to] Can't Post

One way to do it is to read the file, split the current line with commas into an array, and then split again the array elements on dashes into another array or an array of arrays (AoA), and finally use the values with the substr function..

This is an example under the Perl debugger:

Code
  DB<1> $c = "1-3,6-8,10-13" 

DB<2> @a = split /,/, $c;

DB<3> x \@a; # showing the @a array content
0 ARRAY(0x600500ab8)
0 '1-3'
1 '6-8'
2 '10-13'

DB<4> push @b, [split /-/, $_] for @a;

DB<5> x \@b; # the @b AoA content:
0 ARRAY(0x6004f9208)
0 ARRAY(0x600500710)
0 1
1 3
1 ARRAY(0x600626320)
0 6
1 8
2 ARRAY(0x600619d88)
0 10
1 13

DB<6> $string="dogs are really awesome pets";

DB<7> print join "\n", map {substr $string, $_->[0] - 1, $_->[1] - $_->[0] + 1} @b;
dog
are
real


 
 


Search for (options) Powered by Gossamer Forum v.1.2.0

Web Applications & Managed Hosting Powered by Gossamer Threads
Visit our Mailing List Archives