Home: Perl Programming Help: Intermediate:
Can I use grep from the getgo or do I need a module for it?



Wildcard
Novice

Nov 12, 2017, 9:59 AM


Views: 8362
Can I use grep from the getgo or do I need a module for it?

hello there! Wink
I have a code here:

Code
my @num;  

foreach (1..500)
{
if ($_ % 2)
{
push (@num, $_);
}
}
print "\n\n Odd numbers from 1 - 500: \n";
print join ("\t", @num);


My idea: I would like to transfer this into grep, so this way it would be shorter. My editor confirms that "grep" is a valid expression, yet I am not sure how to use this in Perl :)


FishMonger
Veteran / Moderator

Nov 12, 2017, 12:52 PM


Views: 8358
Re: [Wildcard] Can I use grep from the getgo or do I need a module for it?


Code
my @odd = grep { $_ % 2; } 1..20;


or, staying with push instead of grep

Code
my 2odd; 
for (1..20) { push @odd, $_ if $_ % 2; }



BillKSmith
Veteran

Nov 13, 2017, 10:40 AM


Views: 8349
Re: [Wildcard] Can I use grep from the getgo or do I need a module for it?

Perl comes with extensive documentation. Learn to use the documentation reading tool. Type:

Code
perldoc perldoc


To learn about perl's grep function, type:

Code
perldoc -f grep

Good Luck,
Bill


Wildcard
Novice

Nov 13, 2017, 10:49 AM


Views: 8347
Re: [Wildcard] Can I use grep from the getgo or do I need a module for it?

thanks, it helps me a lot!


(This post was edited by Wildcard on Nov 13, 2017, 10:51 AM)


Laurent_R
Veteran / Moderator

Nov 13, 2017, 3:39 PM


Views: 8341
Re: [Wildcard] Can I use grep from the getgo or do I need a module for it?

For the sake of completeness, please note that grep has two possible syntactic forms, so that:

Code
my @odd = grep { $_ % 2; } 1..20;

could also be rewritten as follows:

Code
my @odd = grep $_ % 2, 1..20;

I usually prefer the "block syntax" form (the first one), but the second one can be handy for simple expressions.