Loops Aur foreach
Perl mein ek C-style for loop hota hai familiar three-part header ke saath, plus last (loop se entirely break out karna) aur next (seedha next iteration par skip karna) jisse use mid-flight control kiya jaa sake.
use strict;
use warnings;
for (my $i = 0; $i < 5; $i++) {
next if $i == 2;
last if $i == 4;
print "i=$i\n";
}
i=0 i=1 i=3
i=2 next se skip hota hai (next phir bhi condition re-check karne se pehle $i++ increment run karta hai), aur jab i=4 par last fire hota hai to loop entirely stop ho jaata hai — i=4 khud kabhi print nahi hota. List ko iterate karne ke liye zyada idiomatic tarika hai foreach (ya iska shorter alias, for) my $x (@list) ke saath, jisko kisi index variable ki zaroorat hi nahi hoti:
use strict;
use warnings;
my @colors = ("red", "green", "blue");
foreach my $color (@colors) {
print "Color: $color\n";
}
for my $n (1..5) {
print "N: $n\n";
}
Color: red Color: green Color: blue N: 1 N: 2 N: 3 N: 4 N: 5
1..5 ek range hai — Perl ise list (1, 2, 3, 4, 5) mein expand kar deta hai. Perl mein foreach aur for genuinely same keyword hain; aap kaunsa use karte ho ye purely ek style choice hai. Next: hashes — Perl ka key-value collection.
Practice exercise
foreach my $n (1..10) use karke 1 se 10 tak ke numbers ka sum nikalo, phir sum print karo.