Update:Read the end to see why this is offtopic and not relevant to the question, but in any case don't vote it up! But read on anyway for info about an interesting behavior...Welcome to autovivification. By creating the ref you implicitly tell perl to assume it exists, and so the reference is created, despite the non-existence of the sub. From perldoc perlref:
6. References of the appropriate type can spring into existence if yo
+u
dereference them in a context that assumes they exist. Because we
haven't talked about dereferencing yet, we can't show you any
examples yet.
Skip a few...3. Subroutine calls and lookups of individual array elements arise
often enough that it gets cumbersome to use method 2. As a form of
syntactic sugar, the examples for method 2 may be written:
$arrayref->[0] = "January"; # Array element
$hashref->{"KEY"} = "VALUE"; # Hash element
$coderef->(1,2,3); # Subroutine call
The left side of the arrow can be any expression returning a
reference, including a previous dereference. Note that `$array[$x]
+'
is *not* the same thing as `$array->[$x]' here:
$array[$x]->{"foo"}->[0] = "January";
This is one of the cases we mentioned earlier in which references
could spring into existence when in an lvalue context. Before this
statement, `$array[$x]' may have been undefined. If so, it's
automatically defined with a hash reference so that we can look up
`{"foo"}' in it. Likewise `$array[$x]->{"foo"}' will automatically
get defined with an array reference so that we can look up `[0]' i
+n
it. This process is called *autovivification*.
The same thing has happened to you, but with a sub instead of an array. Just be careful you don't create references to things which don't exist. See chromatic's answer for how to do that with a real sub. If it's an anonymous sub, you probably should never have created the false reference to begin with ;-).
UPDATE: Never mind: merlyn pointed out that autovivification yields a structure with stuff in it, unlike this (the coderef exists, but it's useless). But it's still good to know :-). |