SPUG: spug: What is the idiomatic way to extract first/last item after split?
John W. Krahn
krahnj at telus.net
Tue Jun 28 15:29:51 PDT 2005
Uri London wrote:
>
> What is the idiomatic way to extract first/last item after split?
my ( $first, $last ) = ( split )[ 0, -1 ];
> More interestingly, why #2 doesn't work, while #3 does?
>
> For example:
>
> $path = `cd`;
You should use the Cwd module for that:
use Cwd;
my $path = getcwd;
> # 1. working, but I've been told not very efficient:
> $base = (split /\\/, $path)[-1];
Who told you that? Did you compare it to other methods with the Benchmark module?
> # 2. this isn't working for me. Why???
> $base = pop split /\\/, $path;
pop(), push(), shift(), unshift() and splice() require that the first argument
is an array. They do not work with lists.
perldoc -q "What is the difference between a list and an array"
So if you convert that to an array:
my $base = pop @{[ split /\\/, $path ]};
> # 3. This is similar to above, but does work.
> @tmp = split /\\/, $path;
> $base = pop @tmp;
>
> # 4. Work, but I believe slower:
> ($base) = $path =~ /.*\\([^\\])/;
If speed is your main goal then you should compare various methods using the
Benchmark module. If compatibility and re-use is more important then have a
look at the File::Spec module.
perldoc File::Spec
John
--
use Perl;
program
fulfillment
More information about the spug-list
mailing list