How can I ensure that no null value is assigned to a variable using Perl grep function?
How to put value into a scalar variable when using Perl's开发者_运维百科 grep method?
For example, I have the following code and need to put the value from the per grep method into a scalar variable?
my $variable = grep(/@/,@dataRecord);
if you mean grep
return 1 element than
my ($variable) = grep(/@/,@dataRecord);
else you should use arrayref
my $variable = [ grep(/@/,@dataRecord) ];
If you only need one of the matching elements of @dataRecord
, using grep might not be the most appropriate choice. That is because grep
will check all elements no matter how many matches you want to extract.
You have to first decide which of the potentially more than one matching elements in @dataRecord
you want. If you want the first matching element, you'd be better off using List::MoreUtils::firstval:
firstval BLOCK LIST first_value BLOCK LIST
Returns the first element in LIST for which BLOCK evaluates to true. Each element of LIST is set to
$_
in turn. Returns undef if no such element has been found.
精彩评论