Perl - How to get the number of elements in an anonymous array, for concisely trimming pathnames
- by NXT
Hi Everyone,
I'm trying to get a block of code down to one line. I need a way to get the number of items in a list. My code currently looks like this:
# Include the lib directory several levels up from this directory
my @ary = split('/', $Bin);
my @ary = @ary[0 .. $#ary-4];
my $res = join '/',@ary;
lib->import($res.'/lib');
That's great but I'd like to make that one line, something like this:
lib->import( join('/', ((split('/', $Bin)) [0 .. $#ary-4])) );
But of course the syntax $#ary is meaningless in the above line.
Is there equivalent way to get the number of elements in an anonymous list?
Thanks!
PS: The reason for consolidating this is that it will be in the header of a
bunch of perl scripts that are ancillary to the main application, and I want this
little incantation to be more cut & paste proof.
Thanks everyone
There doesn't seem to be a shorthand for the number of elements in an anonymous
list. That seems like an oversight. However the suggested alternatives were all good.
I'm going with:
lib->import(join('/', splice( @{[split('/', $Bin)]}, 0, -4)).'/lib');
But Ether suggested the following, which is much more correct and portable:
my $lib = File::Spec->catfile(
realpath(File::Spec->catfile($FindBin::Bin, ('..') x 4)),
'lib');
lib->import($lib);