in reply to Initialize variable in BEGIN

Using -n just complicates things for nothing.

With -n:

#!/usr/bin/perl -n use strict; use warnings; our $total; BEGIN { $total = 0; } $total += $_; END { print $total, "\n"; }

Without -n:

#!/usr/bin/perl use strict; use warnings; my $total = 0; while ( <> ) { $total += $_; } print $total, "\n";

One is clearly a million times better.

Replies are listed 'Best First'.
Re^2: Initialize variable in BEGIN
by pfaut (Priest) on Apr 30, 2025 at 17:02 UTC

    It might make more sense if expressed as a one-liner.

    $ for i in {1..10}; do echo $i; done | perl -ne 'BEGIN {our $prod = 1; +} $prod *= $_; END { print $prod,$/; }' 3628800
    90% of every Perl application is already written.
    dragonchild

      I wasn't saying that BEGIN is never useful. I was talking about in the situation at hand.

      But even in your entirely different scenario, does it really make sense?

      perl -nle'BEGIN { $prod = 1; } $prod *= $_; END { print $prod; }'

      vs

      perl -le'$prod = 1; $prod *= $_ while <>; print $prod;'