I am perl beginner, I am reading upon grep
function to filter a list. I came across the following program.
#!/usr/bin/perl
use strict;
use warnings;
# initialize an array
my @array = qw(3 4 5 6 7 8 9);
# first syntax form:
my @subArray = grep { $_ & 1 } @array;
the statement my @subArray = grep { $_ & 1 } @array;
returns odd-numbers in @array
. I didn't understand how the expression($_ & 1
) works. I searched in Google but did not found any useful links.
Is that any kind of special operator ?
Are there any other variants of that EXPR ?
Thanks in Advance.
The “$_” is said to be the pipeline variable in PowerShell. The “$_” variable is an alias to PowerShell's automatic variable named “$PSItem“. It has multiple use cases such as filtering an item or referring to any specific object.
PowerShell's $_ Variable The first point to remember is that $_ is a variable or placeholder. # PowerShell $_ Variable Example Get-Service | Where-Object {$_.name -Match "win"}
$null is an automatic variable in PowerShell used to represent NULL. You can assign it to variables, use it in comparisons and use it as a place holder for NULL in a collection. PowerShell treats $null as an object with a value of NULL. This is different than what you may expect if you come from another language.
Subexpression operator $( )Returns the result of one or more statements. For a single result, returns a scalar. For multiple results, returns an array. Use this when you want to use an expression within another expression.
$_
is the variable holding the currently tested value, &
is the binary AND operator, and 1
is just the number one. This expression combines all the bits of both $_
and 1
with each other by logical AND. So it returns 1 if the value is odd and 0 if the value is even.
As an example, lets assume $_ is 123 then it's binary representation would be 1111011
. The decimal number 1 would be 00000001
, so combining all bits by AND you get
123 = 1111011
1 = 0000001
- AND -
0000001 = 1
Another example 200 & 100
200 = 11001000
100 = 01100100
- AND --
01000000 = 64
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With