BillKSmith has asked for the wisdom of the Perl Monks concerning the following question:
In a previous reply (Re: Use of BEGIN block) , pfaut suggested using BEGIN and END blocks with the Command Switch n . Here is a complete example.
#!perl -n use strict; use warnings; # USAGE: perl np.pl <np.dat BEGIN{ our $total = 0; } our $total; $total += $_; END{ our $total; print $total }
Note that the package variable $total is in scope in all three blocks because it is declared in each with our. Is there a preferred way to do this? I understand that without strict, no declaration is necessary and with the use vars syntax, there is no restriction on scope.
|
---|
Replies are listed 'Best First'. | |
---|---|
Re: Initialize variable in BEGIN
by hippo (Archbishop) on Apr 30, 2025 at 14:50 UTC | |
by ikegami (Patriarch) on Apr 30, 2025 at 16:43 UTC | |
Re: Initialize variable in BEGIN
by Fletch (Bishop) on Apr 30, 2025 at 16:43 UTC | |
Re: Initialize variable in BEGIN
by LanX (Saint) on Apr 30, 2025 at 15:37 UTC | |
Re: Initialize variable in BEGIN
by ikegami (Patriarch) on Apr 30, 2025 at 16:47 UTC | |
Re: Initialize variable in BEGIN
by ikegami (Patriarch) on Apr 30, 2025 at 16:49 UTC | |
by pfaut (Priest) on Apr 30, 2025 at 17:02 UTC | |
by ikegami (Patriarch) on Apr 30, 2025 at 23:54 UTC |