Beefy Boxes and Bandwidth Generously Provided by pair Networks
The stupid question is the question not asked
 
PerlMonks  

Re: Initialize variable in BEGIN

by ikegami (Patriarch)
on Apr 30, 2025 at 16:49 UTC ( [id://11164866]=note: print w/replies, xml ) Need Help??


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;'

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://11164866]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others taking refuge in the Monastery: (3)
As of 2025-07-11 09:19 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found

    Notices?
    erzuuliAnonymous Monks are no longer allowed to use Super Search, due to an excessive use of this resource by robots.