10

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?

2 Answers 2

14

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.

1
  • The compilation order puzzles me a little. Since $var is declared in the BEGIN block first, why is it not erased by the declaration with my later?
    – Nate Glenn
    Jul 3, 2015 at 8:01
2

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.

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.