Different behavior of script in file vs -e

U

usenet

Kindly consider this simple script:

#!/usr/bin/perl -w
@x = qw/foo bar baz/;
print qq{$x[1]\n}
__END__

Which prints "bar\n" (as expected).

AFAIK, this should be the same thing as doing it this way:

perl -we "@x = qw/foo bar baz/; print qq{$x[1]\n}"

but the second case doesn't see $x[1] as a value of an array (it sees
$x as an independent - and undef - scalar and '[1]' as a string literal
- which, of course, generates a warning that "main::x" is used only
once...)

What am I missing here???

Thanks!
 
U

usenet

What am I missing here???

Ha! I just saw where Paul Lalli posted a reply to a completely
different question in a completely different newsgroup
(http://tinyurl.com/ap7lc) which just happens to exactly answer my
question as well.

When I typed:
perl -we "@x = qw/foo bar baz/; print qq{$x[1]\n}"

the shell interprets $x before Perl ever gets to see it.

Paul points out this problem can be avoided by escaping the dollar-sign
or single-quoting the Perl expression.
 
P

Paul Lalli

Kindly consider this simple script:

#!/usr/bin/perl -w
@x = qw/foo bar baz/;
print qq{$x[1]\n}
__END__

Which prints "bar\n" (as expected).

AFAIK, this should be the same thing as doing it this way:

perl -we "@x = qw/foo bar baz/; print qq{$x[1]\n}"

but the second case doesn't see $x[1] as a value of an array (it sees
$x as an independent - and undef - scalar and '[1]' as a string literal
- which, of course, generates a warning that "main::x" is used only
once...)

What am I missing here???

The fact that $ is also the way your shell identifies variables.
Before the above command, try doing:
export x=shell_var
and see what happens.

To work around, either escape the $, or use ' instead of " to surround
your Perl code.

Paul Lalli
 
T

Tad McClellan

Kindly consider this simple script:

#!/usr/bin/perl -w
@x = qw/foo bar baz/;
print qq{$x[1]\n}
__END__

Which prints "bar\n" (as expected).

AFAIK, this should be the same thing as doing it this way:

perl -we "@x = qw/foo bar baz/; print qq{$x[1]\n}"


Try looking at what perl will be seeing:

echo "@x = qw/foo bar baz/; print qq{$x[1]\n}"

but the second case doesn't see $x[1] as a value of an array (it sees
$x as an independent - and undef - scalar


It sees $x as a *shell* variable, not a Perl variable.

and '[1]' as a string literal
- which, of course, generates a warning that "main::x" is used only
once...)

What am I missing here???


Single quotes instead of double quotes for your argument in the shell?
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,055
Latest member
SlimSparkKetoACVReview

Latest Threads

Top