File::Basename comes 'for free' with perl (with the lower p), at least in recent installations. This gives you the advantage to write clean code, not to reinvent the wheel and avoid common pitfalls (which make the
File::Basename solution
simpler IMHO). And lets you not worry about portability, which may not be an issue today, but who knows?
OTOH, you're definitively right on the fast side:
#!/usr/bin/perl
use strict;
use warnings;
use Benchmark qw( cmpthese );
my $tempvalue = 'c:/reports/check/test.txt';
cmpthese( -5, {
file_basename => sub { file_basename($tempvalue); },
fast_and_simple => sub { fast_and_simple($tempvalue); },
});
sub file_basename {
my $tempvalue = shift;
require File::Basename; # Hits performance only once
my ($name, $path) = File::Basename::fileparse($tempvalue);
return $path . "design." . $name;
}
sub fast_and_simple {
my $tempvalue = shift;
my @split = split( '/', $tempvalue );
my $file = pop @split;
return join '/', @split, "design.$file";
}
__END__
Rate file_basename fast_and_simple
file_basename 74479/s -- -58%
fast_and_simple 175981/s 136% --
I dared to make the necessary modifications to your code in order to put it into the benchmark :)
Flavio
perl -ple'$_=reverse' <<<ti.xittelop@oivalf
Don't fool yourself.
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.