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);
lib->import(join('/', splice(@{[split('/', $bin)]}, 0, -4)).'/lib');
Check the splice function.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With