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.
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.