perlfor-loopperlsyn

Perl for loop explanation


I'm looking through perl code and I see this:

sub html_filter {
    my $text = shift;
    for ($text) {
        s/&/&/g;
        s/</&lt;/g;
        s/>/&gt;/g;
        s/"/&quot;/g;
    }
    return $text;
}

what does the for loop do in this case and why would you do it this way?


Solution

  • Without an explicit loop variable, the for loop uses the special variable called $_. The substitution statements inside the loop also use the special $_ variable because none other is specified, so this is just a trick to make the source code shorter. I would probably write this function as:

    sub html_filter {
        my $text = shift;
        $text =~ s/&/&amp;/g;
        $text =~ s/</&lt;/g;
        $text =~ s/>/&gt;/g;
        $text =~ s/"/&quot;/g;
        return $text;
    }
    

    This will have no performance consequences and is readable by people other than Perl.