CGI/Perl Guide | Learning Center | Forums | Advertise | Login
Site Search: in

  Main Index MAIN
INDEX
Search Posts SEARCH
POSTS
Who's Online WHO'S
ONLINE
Log in LOG
IN

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

Post #1 of 5 (908 views)
Can I use grep from the getgo or do I need a module for it? Can't Post

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

Post #2 of 5 (904 views)
Re: [Wildcard] Can I use grep from the getgo or do I need a module for it? [In reply to] Can't Post


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

Post #3 of 5 (895 views)
Re: [Wildcard] Can I use grep from the getgo or do I need a module for it? [In reply to] Can't Post

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

Post #4 of 5 (893 views)
Re: [Wildcard] Can I use grep from the getgo or do I need a module for it? [In reply to] Can't Post

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

Post #5 of 5 (887 views)
Re: [Wildcard] Can I use grep from the getgo or do I need a module for it? [In reply to] Can't Post

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.

 
 


Search for (options) Powered by Gossamer Forum v.1.2.0

Web Applications & Managed Hosting Powered by Gossamer Threads
Visit our Mailing List Archives