Limited Time Offer!

For Less Than the Cost of a Starbucks Coffee, Access All DevOpsSchool Videos on YouTube Unlimitedly.
Master DevOps, SRE, DevSecOps Skills!

Enroll Now

Foreach Vs for Vs while in perl

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

Rajesh Kumar
Follow me
Latest posts by Rajesh Kumar (see all)
Subscribe
Notify of
guest
0 Comments
Newest
Oldest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x