Item 32: Don't confuse anonymous arrays with list literals.The anonymous array constructor [ ] looks very much like the parentheses that surround list literals. They both seem to serve the same purposebuilding lists. However, anonymous array constructors differ from list literals in important ways. An anonymous array constructor returns a reference, not a listThe purpose of an anonymous array constructor is to allow you to create a reference to an array object without having to create a named array:
You can assign the array references created by anonymous array constructors to array variables, but the result is probably not what you want. Be careful to use array variables with lists, and use scalar variables with anonymous array constructors: Don't confuse ( ) and [ ] .
It's easy to make a similar mistake with hashes and the anonymous hash constructor:
An anonymous array constructor creates a list context, but parentheses don'tList and scalar contexts are created by operators and subroutines. The anonymous array constructor is an operator. Parentheses aren't . Just putting parentheses around something will not change a scalar context into a list context. You can see this for yourself: Parentheses do not a list context make.
This is part but not all of the problem that results if you mistakenly assign a would-be list literal instead of an anonymous array constructor to a scalar variable. The other part of the problem is that when you dereference the scalar variable, Perl will take whatever weird value wound up in the scalar and dereference itperhaps interpreting it as a soft reference. Of course, what you are going to get is total nonsense anyway, but these two effects can combine to make the debugging process difficult by treating you to some very strange behaviors up front. For example:
With all this in mind, a clever reader should be able to figure out what's going on here: [2]
|