Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Variable declaration in BEGIN block

Tags:

perl

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?

like image 509
Philippe A. Avatar asked Feb 16 '12 17:02

Philippe A.


People also ask

Can we declare variable in begin block?

You can declare variables only in the DECLARE section of a block. But you can code blocks inside blocks.

Can we declare variable in begin block in Plsql?

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.

How do you declare a variable in SQL block?

Following is the syntax for declaring variable: variable_name [CONSTANT] datatype [NOT NULL] [:= | DEFAULT initial_value]

Should you declare variables at the start?

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.


2 Answers

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.

like image 163
Zaid Avatar answered Nov 06 '22 14:11

Zaid


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.

like image 41
Amadan Avatar answered Nov 06 '22 16:11

Amadan