Perl Script : foreach and @

foreach and @

a foreach statement.
# the loop from cat
foreach my $file (@_) {
print_file $file;
}
When a foreach statement is executed, the expression in parentheses is evaluated once, in list context. Then the first element of the list is assigned to the named variable ($file) and the body of the loop is executed. The body of the loop is executed once for each element of the list, in order.

If you don't provide a loop variable, Perl uses $ as a default. So we could write
the same loop like this:
# the loop from cat
foreach (@_) {
print_file $_;
}

When the angle operator appears in a while loop, it also uses $ as a default loop variable, so we could write the loop in print file like this:
# the loop from print_file
while (<FILE>) {
print $_;
}

Using the default loop variable has one advantage and one disadvantage. The advantage is that many of the built-in operators use $ as a default parameter, so you can leave it out:
# the loop from print_file
while (<FILE>) {
print;
}

The disadvantage is that $ is global, so changing it it one subroutine affects other parts of the program. For example, try printing the value of $ in cat,like this:

# the loop from cat
foreach (@_) {
print_file $_;
print $_;
}


No comments:

Post a Comment