Why does this happen when I grep over an undefined array?

Does anyone know why this is happening?

$ perl -e '@arr = []; print "HELLO." unless grep {/asdf/ =~ $_} @arr;'

Outputs:

HELLO.

But

$ perl -e '@arr = undef; print "HELLO." unless grep {/asdf/ =~ $_} @arr;'

It does not display anything.

It seems to me that both should output "HELLO".

+3
source share
2 answers

You have a couple syntax errors in your code that cause unexpected results.

First, if you need an empty array, you need to write:

# Correct (creates an empty array)
my @array = ();

# Incorrect (creates a one-element array containing a reference to an empty array)
my @array = [];

# Incorrect (creates a one-element array containing the undef element)
my @array = undef;

You also need to cancel the grep condition - the regular expression should be on the right side of the statement =~:

perl -e '@arr = (); print "HELLO." unless grep { $_ =~ /asdf/} @arr;'

If you make these two changes, the code will do what you expect.

+9
source

, grep {$ _ = ~/asdf/}. = ~ , - . grep {/asdf/}, $_ .

, undef regex. ( ) true, undef.

+2

Source: https://habr.com/ru/post/1794580/


All Articles