uninitialized $_ in array element
I have code that contains:
use strict;
use warnings;
use List::Util;
my $index = first { $ARGV[$_] eq "something"; } 0..$#ARGV;
but I get
Use of uninitialized value $_ in arra开发者_运维问答y element at a.pl line 4.
What could cause this ?
As your question lacks information, I can only guess at the real problem, but I managed to get a similar error with:
C:\perl>perl -MList::Util -we "$a= first { $ARGV[$_] eq 'some' } 0..$#ARGV; print $a" foo bar some thing
Use of uninitialized value $_ in array element at -e line 1.
Can't call method "first" without a package or object reference at -e line 1.
The error does not appear if I use List::Util qw/first/
explicitly, or if I use the full package name: List::Util::first
. So, my guess is that the first
function is not properly imported, and does not recognize the list after the code block, leaving $_
uninitialized.
The error most likely lies elsewhere in your code.
Are you familiar with
new Class @args
That's called the "indirect method notation". It means
Class->new(@args)
If first
isn't declared,
first { $ARGV[$_] eq "something"; } 0..$#ARGV;
is treated as an indirect method call, so it's equivalent to
{ $ARGV[$_] eq "something"; }->first(0..$#ARGV);
{ ... }
constructs a hash, which is neither a package name or an object reference as required by a method call, thus
Can't call method "first" without a package or object reference
The solution: declare first
by importing it.
精彩评论