Beefy Boxes and Bandwidth Generously Provided by pair Networks
We don't bite newbies here... much
 
PerlMonks  

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:

Monks,

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.

Thanks.

Comment on accessing a part of a string
Download Code
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 );
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/')

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others having an uproarious good time at the Monastery: (17)
As of 2015-07-03 12:09 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The top three priorities of my open tasks are (in descending order of likelihood to be worked on) ...









    Results (52 votes), past polls