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--
|