Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how does it works "$_ & 1" in perl

Tags:

arrays

perl

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.

like image 423
V A Ramesh Avatar asked Apr 17 '13 12:04

V A Ramesh


People also ask

What does $_ mean?

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.

What does _$ mean in PowerShell?

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"}

What does $null mean in PowerShell?

$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.

What does $() do in PowerShell?

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.


1 Answers

$_ 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
like image 95
tauli Avatar answered Sep 18 '22 06:09

tauli