Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl-Sensitive Sunglasses

accessing a part of a string

by uday_sagar (Scribe)
on May 18, 2012 at 11:03 UTC ( #971273=perlquestion: print w/replies, xml ) Need Help??
uday_sagar has asked for the wisdom of the Perl Monks concerning the following question:


my $out = substr("some/very/varied_length/string",-6);

is giving me "string" in $out.

But I want the other part "some/very/varied_length/" Here I am interested in a general code which works with the changes in length of "varied_length" of the above string.


Replies are listed 'Best First'.
Re: accessing a part of a string
by Anonymous Monk on May 18, 2012 at 11:12 UTC
    If you are manipulating filesystem paths, use the Path::Class::Dir module and its dir_list method.

    If you are manipulating URIs, use the URI module and its path_segments method.

    If it is neither, simply use a regular expression that captures everything up to the last /.

    'some/very/varied_length/string' =~ m|(.*/)| # expression returns ('some/very/varied_length/')
Re: accessing a part of a string
by phenom (Chaplain) on May 18, 2012 at 11:11 UTC
    You want everything but a part of the string? You could play with this and alter it as needed:
    my $string = 'some/very/varied_length/string'; my $subs = substr( $string, 0, length($string) - 6 ); say $subs;
    Don't forget to add the OFFSET portion of substr.
      substr( $string, 0, length($string) - 6 );

      can also be written as

      substr( $string, 0, -6 );

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://971273]
Approved by kcott
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others meditating upon the Monastery: (4)
As of 2018-06-22 21:38 GMT
Find Nodes?
    Voting Booth?
    Should cpanminus be part of the standard Perl release?

    Results (124 votes). Check out past polls.