in reply to defined class variable with Moose

G'day Hosen1989,

I suspect you may be mixing (and consequently, confusing) this type of Moose syntax:

has attribute => ( default => sub { 0 }, );

with normal Perl syntax for creating key-value pairs:

{ default => 0, }

sub { 0 } is a code reference.

For your simpler cases, like

description => sub{0}

you could just use

description => 0

However, regardless of the complexity of the code within sub { ... }, what you really want is the return value when that code is executed. For that, use

sub { ... }->()

Consider these three one-liners:

$ perl -wE 'my $x = { y => 0 }; say $x->{y}' 0
$ perl -wE 'my $x = { y => sub { 0 } }; say $x->{y}' CODE(0x7f8c34026a60)
$ perl -wE 'my $x = { y => sub { 0 }->() }; say $x->{y}' 0

-- Ken

Replies are listed 'Best First'.
Re^2: defined class variable with Moose
by Hosen1989 (Scribe) on Jun 26, 2015 at 20:02 UTC

    Hi there,

    Thanks for you reply.

    I can see that my code hare are somewhat confusing, but I use description => sub{0} in-stand of description => 0 to keep the consist with other item in my @parserArray, as i need them to be in the same format where i use each item in this array to read some part of my raw file.

    As my question here was not clear,let me ask again: but what i need to do is to define variable in my class that contain some predefined data (mix of array/hash/scalar/code).

    BR

    Hosen

      "but I use description => sub{0} in-stand of description => 0 to keep the consist with other item in my @parserArray, ..."

      I only said "you could just use", not "you must use". That was just a suggestion. By all means, keep them consistent.

      The main thrust of what I was pointing out, was that a value of 'sub { 0 }->()', or just a plain old '0', will evaluate to 0; however, the 'sub { 0 }' that you showed evaluates to something like CODE(0x7f8c34026a60).

      "... what i need to do is to define variable in my class that contain some predefined data"

      Isn't @parserArray_type_01 just such a variable with predefined data?

      I don't see a reason why you can't use something like $parserArray_type_01[$index]{$key} in your code (whether it uses Moose or not).

      Please post a short piece of code (10-20 lines) that demonstrates where such a variable is causing problems.

      -- Ken