Damn you. I was going to post that. :-P

Yeah, I wouldn't have used the s/// if I'd remembered rindex. You'll have to forgive me, I was tired last night (yay 12 hours of overtime...).

Anyway, here's my version of the substr/rindex version. It uses the same algorithm as my regexp version (ie, it's still destructive to $str) and is a little cleaner than yours (but not much):

# MAKE SURE $str IS A _COPY_ OF YOUR DATA!!! my $str = "/One/Two/Three"; my @paths = (); while($str) { # If you don't want @push to include the current # cat (ie, "/One/Two/Three"), put this line after # the substr. But then you'll have as the last # element an empty string. Put a "last unless($str);" # between the substr and the push to avoid that. push @paths, $str; # Save everything from the begining of the string # up to, but not including, the last /. $str = substr($str, 0, rindex($str, '/')); } print "$_\n" for @paths;

This prints:

/One/Two/Three /One/Two /One

bbfu
Seasons don't fear The Reaper.
Nor do the wind, the sun, and the rain.
We can be like they are.


In reply to (bbfu) (substr and rindex) Re(4): Messing with (my head) a substring by bbfu
in thread Messing with a substring by psypete

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.