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

i have this gode to get the last 1000 bases of sequence but it's not working correctly.

my $ x_end = $end + 1000;

print "$x_end and $end\n";

my $sub = substr ($seq, $end, $x_end);

my $l = length $sub;

print $sub;
The length of sub should be 1000 but isn't I put the print lines n to check i wasn't being dopey, but i am! Why isn't this working as I'd expect?

Replies are listed 'Best First'.
Re: why is substr behaving odd?
by !1 (Hermit) on Nov 18, 2003 at 15:37 UTC

    substr can take a third parameter indicating length, not ending position. In other words:

    my $sub = substr ($seq, $end, 1000);

    I hope this helps you with your problem.

Re: why is substr behaving odd?
by bschmer (Friar) on Nov 18, 2003 at 15:42 UTC
    I'm a little confused by your problem but I'll offer the following advice anyways. If you simply want the last 1000 characters of a string the following should be sufficient:
    my $sub = substr($seq, -1000);
    Your substr doc should point out that negative positions work from the end of the string.
Re: why is substr behaving odd?
by ptkdb (Monk) on Nov 18, 2003 at 15:45 UTC
    In addtion to !1's observation, if you were to turn on warnings(-w or use warnings) I'm wondering if the 'substr' line might not give you some grief about an undefined variable. Also keep in mind that substr is not going to 'pad' your result. So if there isn't 1000 bases(assumed to be 1 char each), you won't get substr 1000 long

    .

    ## ## Taking the last N elements off the end of a string ## use strict ; use warnings ; my($s) = '0123456789' ; print substr($s, -5), "\n" ;
Re: why is substr behaving odd?
by ysth (Canon) on Nov 18, 2003 at 15:55 UTC
    If there aren't that many characters left after $end, substr will just return what there are. Do you want: $sub = substr($seq, -1000)?
      thanks everyone!
A reply falls below the community's threshold of quality. You may see it by logging in.