Using Grep in Perl

classic Classic list List threaded Threaded
3 messages Options
Reply | Threaded
Open this post in threaded view
|

Using Grep in Perl

Smruti Mohanty
#!/usr/bin/perl -w
use strict;

my @numbers = (28, 49, 1000, 4, 25, 49, 529);

my @arr1 = grep{($_/sqrt$_)==0}@numbers;

print "@arr1";

I am trying to find perfect squares in the list @numbers using the grep command...
But the above code doesn't give any output! Why?
Reply | Threaded
Open this post in threaded view
|

Re: Using Grep in Perl

Smruti Mohanty
I got it ...

$_%sqrt($_)==0
Reply | Threaded
Open this post in threaded view
|

Re: Using Grep in Perl

Guru
Administrator
In reply to this post by Smruti Mohanty
A crude way of doing it:

my @arr1 = grep{sqrt !~/\./}@numbers;

If a number is a perfect square, its square root will be a full number(say 7), else will contain a fraction part(say 7.15). The above regex checks whether the square root contains a dot or not.

Note: sqrt with no argument takes $_ as argument.