Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Hi all, how can I get a subtring from a bigger string, when I know the starting and ending positions of the substring?
For instance, if you have a string with 50 characters, and you want to get the substring from character#12 - character#27 ,what do you do?
Thank you!
  • Comment on get substring when you know START and END???

Replies are listed 'Best First'.
Re: get substring when you know START and END???
by jwkrahn (Abbot) on May 27, 2006 at 21:13 UTC
    You can use substr:
    my $start = 12; my $end = 27; #my $substring = substr $string, $start - 1, $end - 1; #Ooops, that should be: my $substring = substr $string, $start - 1, $end - ( $start - 1 );
Re: get substring when you know START and END???
by swampyankee (Parson) on May 27, 2006 at 21:16 UTC

    First, read the perl docs (try perldoc -f substr). You would use substr. In your case, the code would look like:

    use strict; use warnings; # always a good idea my $start = 12; my $end = 27; my $string = 'a string at least 27 characters long with any random cha +racters'; my $substring = substr($string, $start, ($end - $start));

    emc

    "Being forced to write comments actually improves code, because it is easier to fix a crock than to explain it. "
    —G. Steele
Re: get substring when you know START and END???
by Anonymous Monk on May 27, 2006 at 21:46 UTC
    Say you have
    $seq= 'ABCDEFGHIJKLM';
    $start=5;
    $end=7;
    As I can see, I want to print 'EFG'...
    By using substr, I print 'EFGHIJK'.

      So you are using 1 based numbering and you need to do the following:

      use strict; use warnings; my $seq= 'ABCDEFGHIJKLM'; my $start=5; my $end=7; print substr $seq, $start - 1, ($end - $start) + 1;

      Prints:

      EFG

      DWIM is Perl's answer to Gödel

      You've had about 3 people explain to you how to get the length of a string given its start and end points. What more do you need?

      emc

      "Being forced to write comments actually improves code, because it is easier to fix a crock than to explain it. "
      —G. Steele
Re: get substring when you know START and END???
by Anonymous Monk on May 27, 2006 at 22:56 UTC
    It's correct now... Thanx GrandFather :)
A reply falls below the community's threshold of quality. You may see it by logging in.