in reply to regular expression and grep function questions
What does "\z" mean in Perl?
Some people use the flags /xms as the default starting point for every regex. If you do that, then:\A \z --beginning and end of the entire string ^ $ --beginning and end of a "line" within the string
Then just forget about \Z, which is unnecessary.
use strict; use warnings; use 5.010; my $string = "HELLO\nWORLD\nGOODBYE"; my @patterns = ( '\A (.)', #Match start of entire string followed by any char '^ (.)', #Match start of every line followed by any char '(.) \z', #Match any char followed by end of the entire string '(.) $', #Match any char followed by end of a line ); for my $pattern (@patterns) { my @matches = $string =~ /$pattern/gxms; say "@matches"; say '*' x 20; } --output:-- H ******************** H W G ******************** E ******************** O D E ********************
I remember grep only takes two input variables, one is the expression and the other one is an array.
Actually,
grep BLOCK LIST
A list is a series of comma separated values, e.g. 1, 'a', 2, 'b'. So if you give perl an array along with a scalar value in a spot where perl expects a list, then perl extracts the values from the array and adds the scalar value to the end, creating one list.
That phenomena happens in a lot of places in perl. As hippo explained, look what happens if you call a sub with two arrays:
use strict; use warnings; use 5.010; sub do_stuff { my @x = shift; my @y = shift; say "@x"; say "@y"; } my @arr1 = (10, 20); my @arr2 = ('a', 'b'); do_stuff(@arr1, @arr2);
What do you expect the output to be?
When you call the function perl 'unwinds' the first array into a list of comma separated values, and perl does the same with the second array, creating one big list--as if you called the function like this:
do_stuff(10, 20, 'a', 'b');
That list then gets assigned to the array named @_. So when you shift one value from @_ and assign the value to the array @x, it's as if you wrote:
my @x = 10;
And in that line, because there is an array on the left, which expects a list on the right, perl converts the scalar 10 to the list (10) giving you this:
my @x = (10);