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

I have a string:
/directory/directory/some-file.html

What is the most efficient way to drop off the:
some-file.html

Thanks
-- paul

Edit 2001-06-02 by mirod: changed the title

Replies are listed 'Best First'.
Re: URL Help
by myocom (Deacon) on Jun 01, 2001 at 23:15 UTC
(jeffa) Re: URL Help
by jeffa (Bishop) on Jun 01, 2001 at 23:16 UTC
    I would skip a regex solution and use substr and rindex:
    my $url = qq|/directory/directory/some-file.html|; print substr($url, 0, rindex($url,'/')),"\n";

    UPDATE:

    I just saw tye mention:

    (split('/',$url))[-1]
    in the chatterbox. Negative indexing++.

    Sheer boredom has settled in me today, so i have decided to run some benchmarks. You did mention 'efficient' after all.

    use strict; use Benchmark; use File::Basename; my $url = qq|/directory/directory/some-file.html|; timethese(500000, { 'substr' => sub { return substr($url, 0, rindex($url,'/')) }, 'split' => sub { return (split('/',$url))[-1] }, 'module' => sub { return basename($url) }, }); =for benchmark_results Benchmark: timing 500000 iterations of module, split, substr... module: 33 wallclock secs (33.03 usr + 0.10 sys = 33.13 CPU) split: 5 wallclock secs ( 5.44 usr + -0.01 sys = 5.43 CPU) substr: 1 wallclock secs ( 1.74 usr + 0.00 sys = 1.74 CPU) (linux kernal 2.2.14-5.0, dual 450MHz) =cut
    So what does this mean? Just because the substr method is faster is not a reason to pick it over File::Basename.

    The main reason is portability. Since we are dealing with URL's, we are guaranteed that forward slashes will be used, but if you are dealing with directory paths, the substr method will not portable between Unix platforms and Windows platforms.

    And i bet the reason you can't use modules is not because of a work restriction - this was a homework question wasn't it? Doh! Oh well.

    Jeff

    R-R-R--R-R-R--R-R-R--R-R-R--R-R-R--
    L-L--L-L--L-L--L-L--L-L--L-L--L-L--
    
      Jeff,
      Your solution worked great!
      I couldn't use the other suggestions, because I am not allowd to use any packages :(
      thanks again!!

      -- paul

        Sounds like an artificial restriction, if you ask me. File::Basename comes with the default installation of Perl...

Re: URL Help
by buckaduck (Chaplain) on Jun 01, 2001 at 23:17 UTC
    use File::Basename; my $dirstr = "/directory/directory/some-file.html"; $dirstr = dirname($dirstr);

    Note that the trailing slash will be cut off.

    buckaduck

Re: URL Help
by Big Willy (Scribe) on Jun 02, 2001 at 00:17 UTC
    Assuming your path is stored in $path, this would put it in $1.
    $path =~ #^(.+/)#;
    I justed used the # so as not to conflict with the / in the expression.