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

Hello everyone , this would be a very very simple question but for some reason i am not getting it , i have a variable look like this $a=/export/home/test/great I want to exclude the last /great out of it and put it back in the same varibale so $a=/export/home/test/great so is there a way to do that please do let me know thanks

Replies are listed 'Best First'.
Re: help on reg ex
by artist (Parson) on May 07, 2003 at 15:22 UTC
    $a = '/export/home/test/great'; if($a =~ m/(.*)\/(.*?)$/){ $dir = $1; $file = $2; } print "$a\n$dir\n$file\n"; __END__ /export/home/test/great /export/home/test great
    Now, what is the purpose behind it..? is it to get directory out of the total path or just the filename?. Use File::Basename. If you give more contextual hints, more help is awaiting for you.

    artist

Re: help on reg ex
by Improv (Pilgrim) on May 07, 2003 at 15:21 UTC
    I'm assuming your second example of $a is a typo and should have read $a = '/export/home/test'. If you want to chop out great specifically, you can do:
    $a =~ s/\/great$//;
    If you want to generically remove the last element, and save it to $bar, you can do:
    $a =~ s/(\/.*)$//; $bar = $1;
    I hope this helps.
      Your example: would put in $bar everything starting from the first slash. You should instead do:
      $a =~ s#(/[^/]*)$##; $bar = $1;

      -- zigdon

        Oops, you're right. My bad -- I don't know what I was thinking :) You provide a good example to the user of a case where it's a good idea to use a nonstandard regex delimiter, BTW. Cool.
Re: help on reg ex
by svsingh (Priest) on May 07, 2003 at 15:39 UTC
    I'm not really clear on what you're asking for with extracting /great and putting it back. Both the inital and resulting $a's in your question look the same to me.

    Here's what I came up with...

    my $a = '/export/home/test/great'; $a =~ / (.*) (\/[^\/]*) /x; my $front = $1; my $back = $2; print "a: $a\n"; print "front: $front\n"; print "back: $back\n";

    Note: I'm using /x to add some whitespace to the regex for clarity. You can ignore the spaces.

    That returns...

    a: /export/home/test/great front: /export/home/test back: /great

    I think the other solutions are affected by regex greed. So they'll pull out the longest string starting with a slash. If I'm oversimplifying things, then I'm sorry.

    I hope this helps.

      I must have forgotten to thank you , thanks for helping me out
Re: help on reg ex
by Joost (Canon) on May 07, 2003 at 15:23 UTC
    I assume you mean:
    $a="export/home/test/great/great";
    you can do:
    $a =~ s#/great\z##; print $a; # prints "/export/home/test/great"
    (that \z means 'the end of the string')
    -- Joost downtime n. The period during which a system is error-free and immune from user input.