rajeshkumar created the topic: foreach Vs for Vs while in perl
Definition 1:
In the while loop, Perl reads a line of input, puts it into a variable, and runs the body of the loop. Then, it goes back to find another line of input.
But in the foreach loop, the line-input operator is being used in a list context (since foreach needs a list to iterate through). So it has to read all of the input before the loop can start running.
That difference will become apparent when the input is coming from your 400 MB web server logfile! It’s generally best to use code like the while loop’s shortcut, which will process input a line at a time, whenever possible. Source-The Llama book
Definition 2:
What Alex Reynolds says in stackoverflow.com
For most purposes, you probably won’t notice a difference.
However, foreach reads each line into a list (not an array) before going through it line by line, whereas while reads one line at a time.
As foreach will use more memory and require processing time upfront, it is generally recommended to use while to iterate through lines of a file.
In addition to the previous responses, another benefit of using while is that you can use the $. variable. This is the current line number of the last filehandle accessed
while ( my $line =
if ( $line =~ /some_target/ ) {
print "Found some_target at line $.\n";
}
}
Regards,
Rajesh Kumar
Twitt me @ twitter.com/RajeshKumarIn
I’m a DevOps/SRE/DevSecOps/Cloud Expert passionate about sharing knowledge and experiences. I am working at Cotocus. I blog tech insights at DevOps School, travel stories at Holiday Landmark, stock market tips at Stocks Mantra, health and fitness guidance at My Medic Plus, product reviews at I reviewed , and SEO strategies at Wizbrand.
Please find my social handles as below;
Rajesh Kumar Personal Website
Rajesh Kumar at YOUTUBE
Rajesh Kumar at INSTAGRAM
Rajesh Kumar at X
Rajesh Kumar at FACEBOOK
Rajesh Kumar at LINKEDIN
Rajesh Kumar at PINTEREST
Rajesh Kumar at QUORA
Rajesh Kumar at WIZBRAND