In a script like the following, is it possible without dropping 'my' to effectively declare 'var' only once and have it visible outside the BEGIN block?
echo -e "\n\n\n" | \
perl -lne 'BEGIN { my $var="declared & initialized once" } print $var'
Also, why declaring var without 'my' makes it visible outside the BEGIN block?
You can declare variables only in the DECLARE section of a block. But you can code blocks inside blocks.
You can declare constants and variables in the declarative part of any PL/SQL block, subprogram, or package. Declarations allocate storage for a value, specify its datatype, and specify a name that you can reference. Declarations can also assign an initial value and impose the NOT NULL constraint.
Following is the syntax for declaring variable: variable_name [CONSTANT] datatype [NOT NULL] [:= | DEFAULT initial_value]
It's best to declare variables when you first use them to ensure that they are always initialized to some valid value and that their intended use is always apparent.
Place a my $var;
before the BEGIN
block:
$ perl -le 'my $var; BEGIN { $var = "declared"; } print $var;'
declared
my
gives the variable lexical scope, so $var
is not defined in your example outside the BEGIN
block. Removing the my
effectively makes it a global variable, which is accessible across the script after assignment.
Also, why declaring var without 'my' makes it visible outside the BEGIN block?
You're not declaring it then. It is autodeclared as global, if you're not using use strict
(which prevents the declaration by default). In a one-liner, strict
hurts more than it helps; I'm perfectly fine with not doing a declaration in such a context.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With