http://www.perlmonks.org?node_id=150141

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

I have a string "$var = "one/two/three/four/five/six/";"
(note the last ' / ' on it. I need to be able to remove just the last item, leaving the rest as a string,
"$var2 = "one/two/three/four/five/";

Is there a simple way to do this?

Replies are listed 'Best First'.
Re: remove the part of the string that is after the second to last '/'
by dragonchild (Archbishop) on Mar 07, 2002 at 21:46 UTC
    $var =~ s![^/]*/$!!;

    Have fun! :-)

    ------
    We are the carpenters and bricklayers of the Information Age.

    Don't go borrowing trouble. For programmers, this means Worry only about what you need to implement.

Re: remove the part of the string that is after the second to last '/'
by virtualsue (Vicar) on Mar 07, 2002 at 23:20 UTC
    There are lots of ways to do it, and this thread will likely fill up with them. I can't help noticing that what you're looking for resembles the unix command "dirname", however.
    chomp($str = `dirname $str`);
    Yes, it's silly and not portable. I'm just covering a base here. :-)

    The dirname method in File::Basename would be a good choice if you are in fact manipulating directory paths. This module is reasonably platform independent and part of the core Perl distribution.

    use File::Basename; my $dir = dirname($filename);
    Do "perldoc File::Basename" for more information.
Re: remove the part of the string that is after the second to last '/'
by ajwans (Scribe) on Mar 07, 2002 at 21:46 UTC
    How about

    $string =~ s!^(.*/).*?/$!$1!;

    Guess I just prefer non-greedy matching to negated character classes.

    1. dude, what does mine say?
    2. "sweet", what about mine?
    3. "dude", what does mine say?
    4. GOTO 2
Re: remove the part of the string that is after the second to last '/'
by abaxaba (Hermit) on Mar 08, 2002 at 06:52 UTC
    #If you don't need the original string: $var =~ s|[^/]+/$||; #If you would like to leave $var unchanged: ($newVar) = $var=~ m|(.+/)[^/]+/$|;
Re: remove the part of the string that is after the second to last '/'
by SgtClueLs (Novice) on Mar 07, 2002 at 22:33 UTC
    Or the non cool way! Regular expression are for weenies! :)
    $var = "one/two/three/four/five/six/"; split /\//, $var; pop; $var = $var . $_ foreach(@_);
      You weenie! You used a regular expression! :)

      I think I like this way of avoiding regexes better:
      substr($var, rindex($var, '/', length($var) - 2)) = '';

      ++ vs lbh qrpbqrq guvf hfvat n ge va Crey :)
      Nabgure bar vs lbh qvq fb jvgubhg ernqvat n znahny svefg.
      -- vs lbh hfrq OFQ pnrfne ;)
          - Whreq