Perl: using Class::Struct vs explicit Perl object reference -


i'm new perl please bear me... saw script uses class::struct such:

class::struct

#!/usr/bin/perl  package animal;  use strict; use warnings;  use class::struct;  struct animal => {   species => '$' };  sub species {   print "in species"; }  package main;  $x; $x = animal->new; 

output: in species

my understanding shortcut following:

perl object reference

#!/usr/bin/perl  package animal;  use strict; use warnings;  sub new {   $class = shift;   $self = {};   bless $self, $class;   return $self; }  sub species {   print "in species"; }  package main;  $x; $x = animal->new; 

output:

i didn't expect class::struct example output: in species. seems indicate sub/methods listed in struct run when running animal->new i'm not sure why case. expected class::struct create accessor methods , provide me new method getting object reference.

so questions are:

  • is understanding correct?
  • why class::struct running methods on initialisation?
  • am missing anything?

update previous perl 5.18.0 not default behaviour illustrated here: https://rt.perl.org/public/bug/display.html?id=29230

taken class::struct's documentation:

each element in struct data has accessor method, used assign element , fetch value. default accessor can overridden declaring sub of same name in package. (see example 2.)

and later on (emphasis added):

scalar ('$' or '*$')

the element scalar, , default initialized undef (but see "initializing new").

the accessor's argument, if any, assigned element.

the new call tries set species property undef calling accessor sub species defined in package.

as dumper call in accessor routine shows:

sub species {   print "in species\n";   use data::dumper;   print dumper(\@_); } 

outputs:

in species $var1 = [       bless( {}, 'animal' ),       undef     ]; 

Comments

Popular posts from this blog

Email notification in google apps script -

c++ - Difference between pre and post decrement in recursive function argument -

javascript - IE11 incompatibility with jQuery's 'readonly'? -