Il primo arg che si dà a grep deve valutare come vero o falso per indicare se ci fosse una corrispondenza. Così dovrebbe essere:
# note that grep returns a list, so $matched needs to be in brackets to get the
# actual value, otherwise $matched will just contain the number of matches
if (my ($matched) = grep $_ eq $match, @array) {
print "found it: $matched\n";
}
Se è necessario far corrispondere su un sacco di valori diversi, ma potrebbe anche essere la pena per voi di prendere in considerazione di mettere i dati array
in una hash
, dal momento che gli hash consentono di fare questo in modo efficace, senza dover scorrere l'elenco.
# convert array to a hash with the array elements as the hash keys and the values are simply 1
my %hash = map {$_ => 1} @array;
# check if the hash contains $match
if (defined $hash{$match}) {
print "found it\n";
}
Penso che si potrebbe ri-parola che questo sia chiaro - anche se posso vedere quello che vuoi dire su rilettura, suona inizialmente come voi stiamo dicendo che 'grep' nel contesto scalare restituisce la lunghezza di' @ array'. Come intendi (giustamente), restituisce il numero di volte in cui l'espressione/blocco è vera. Se l'espressione è * solo una variabile * - cioè nessun confronto effettivo, solo la variabile '$ match', allora è vera per ogni elemento se la variabile stessa è vera (non vuota, diversa da zero ecc.) –
@ Sam : Ho provato a riformularlo, speriamo che sia più chiaro ora. –
@eugeney che mi legge molto meglio, fantastico! –