Beefy Boxes and Bandwidth Generously Provided by pair Networks
No such thing as a small change

Re: variable scope affects variables in crace shell escapes

by DaveH (Monk)
on Mar 30, 2003 at 11:03 UTC ( #246714=note: print w/replies, xml ) Need Help??

in reply to variable scope affects variables in crace shell escapes


I did a double take on this one, because at first it wasn't at all clear to me what was happening. I think that most of this confusion was because you called "" (double quotes) shell escapes. What you are referring to is not "shell escaping", it is "double quote interpolation".

Anyway, the problem you are having seems to be related to Perl's DWIM ("Do What I Mean") attitude to string interpolation, and it auto-vivifying arrays when you don't want them. In your example code, you are auto-vivifying two arrays: @a and @c. If you want to know more details, I suggest inserting the following at the top of your script:

use strict; use warnings; use diagnostics;

Fortunately, there is a very simple solution - if you don't want Perl to treat square brackets ("[" and "]") as array subscripts, then escape them with a backslash ("\") in your strings.

$a = 'name'; $b = 5; my $c = 'name'; my $d = 5; print "$a\[$b\]" eq "$c\[$d\]" ? "ok\n" : "booger\n";

(As an aside, you should really try to avoid $a and $b as variable names. Whilst I'm sure they were used just as an illustration, these are reserved variables which are used in the 'sort' built-in function. Although "use strict" won't complain about them, there is a good reason for this: they are always package global symbols. Moral: always use 'my' and stay away from $a and $b.)

I hope that helps.


-- Dave :-)


Replies are listed 'Best First'.
Re: Re: variable scope affects variables in brace shell escapes
by colink (Novice) on Mar 31, 2003 at 05:30 UTC
    Well, I think you missed the essence of my question. "shell escapes" are straight from the perldata manpage:

    As in some shells, you can enclose the variable name in braces to disambiguate it from following alphanumerics (and underscores). You must also do this when interpolating a variable into a string to separate the variable name from a following double‐colon or an apostrophe, since these would be otherwise treated as a package separator.

    $a[$b] is the 6th element of the @a array ${a}[$b] is supposed to be the same as join '', $a, '[', $b, ']';

    but if you declare the variable $a to be lexically scoped with my then perl seems to want to force them the construct to be considered as an array, which is wrong.

Log In?

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://246714]
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others scrutinizing the Monastery: (4)
As of 2023-03-25 16:44 GMT
Find Nodes?
    Voting Booth?
    Which type of climate do you prefer to live in?

    Results (63 votes). Check out past polls.