SPUG: spug: What is the idiomatic way to extract first/last item after split?
Colin Meyer
cmeyer at helvella.org
Tue Jun 28 15:22:17 PDT 2005
[I meant to send this reply to the list ...]
On Tue, Jun 28, 2005 at 03:00:38PM -0700, Uri London wrote:
>
> What is the idiomatic way to extract first/last item after split?
>
> More interestingly, why #2 doesn't work, while #3 does?
>
> For example:
>
> $path = `cd`;
>
>
> # 1. working, but I've been told not very efficient:
>
> $base = (split /\\/, $path)[-1];
>
This is plenty efficient. To compare efficency, see the
Benchmark module.
>
> # 2. this isn't working for me. Why???
>
> $base = pop split /\\/, $path;
pop only works on an array. An array variable stores a list,
but a list isn't the same as an array.
You could create an annonymous array reference, and dereference
it, but it gets to look fairly ugly:
$base = pop @{ [ split /\\/, $path ] };
>
> # 3. This is similar to above, but does work.
>
> @tmp = split /\\/, $path;
>
> $base = pop @tmp;
This works because your are storing the list in an array, which
then works as expected with pop().
>
> # 4. Work, but I believe slower:
>
> ($base) = $path =~ /.*\\([^\\])/;
Try playing Benchmark. Then you can know instead of believing. You
can believe me when I say that it's more satisfying to know. :)
It really is well worth your time to do simple benchmarks. After using
Perl heavily for more than 10 years, I am still sometimes surprised
by benchmarking similar ways of doing things.
Have fun,
-Colin.
More information about the spug-list
mailing list