Thursday, November 28, 2019

Beginning Perl Tutorial on Foreach Loop

Beginning Perl Tutorial on Foreach Loop The foreach loop is a control structure thats tailor-made to process Perl lists and hashes. Just like the for loop, foreach steps through each element of an array using an iterator. How to Step Through an Array in Perl With Foreach Rather than using a scaler as an iterator,  foreach uses the array itself. For example: You see that this gives the same output as printing the array myNames in its entirety: If all you want is to dump out the contents of the list, you could just print  it. In that case, use the foreach loop to make the output a bit more readable. Youll see that this code creates cleaner output by printing a new line after each item in the list. A Cleaner Foreach Loop The previous example used $_ to print each element of the list. Using this default implied scalar ($_) makes for shorter code and less typing, but it isnt always the best solution. If youre aiming for a highly readable code or if your  foreach  loop is complex, you might be better off assigning a  scalar  as your iterator. There are only two differences: the scalar $name between the  foreach  and the list and the replacement of the default scalar with it inside the loop. The output is exactly the same, but the code is slightly cleaner. Keep in mind: A  foreach  loop is a Perl control structure.It is used to step through each  element of an array.

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.