Beefy Boxes and Bandwidth Generously Provided by pair Networks
Pathologically Eclectic Rubbish Lister
 
PerlMonks  

Re: Re: (bbfu) Re: Messing with (my head) a substring

by repson (Chaplain)
on Apr 01, 2001 at 15:01 UTC ( #68819=note: print w/ replies, xml ) Need Help??


in reply to Re: (bbfu) Re: Messing with (my head) a substring
in thread Messing with a substring

If you'd like a non regex solution, try using index and substr which, while less flexible than regexen can be clearer/better in a few situations.

my $str = "/One/Two/Three"; my @paths = ($str); while ($paths[-1] =~ tr#/#/# > 1) { push @paths, substr($paths[-1], 0, rindex($paths[-1], '/')); } print "$_\n" for @paths;
A few points of explanation: $paths[-1] means the last element of the array. The tr function returns the number of characters it transformed. The rindex function returns the character number where a substring last appears and the substr function returns part of a string. The push function adds items to the end of an array.

All these things are in the documentation that comes with perl, you just have to put them together.


Comment on Re: Re: (bbfu) Re: Messing with (my head) a substring
Select or Download Code
(bbfu) (substr and rindex) Re(4): Messing with (my head) a substring
by bbfu (Curate) on Apr 02, 2001 at 03:39 UTC

    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.

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others browsing the Monastery: (15)
As of 2014-10-30 13:42 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    For retirement, I am banking on:










    Results (208 votes), past polls