postman has asked for the wisdom of the Perl Monks concerning the following question:

I need the benefit of your advice once again fellow monks ... I'm try to add a list of object variables and values all at once, but can't quite figure it out except by the most laborious way of adding them one at a time. The relevant part of my code is this:
use strict; sub new { my $class_name = shift; my $self = {}; #want to do something like this ... @self->{sec,min,hour,mday,mon,year,wday,yday,isdst}=localtime(); bless ($self,$class_name); }
I've a feeling it should be something along the lines of  @hash{@keys} = @values; which I've seen on another thread, but I can't quite get there. TIA

Replies are listed 'Best First'.
Re: adding an array of instance variables and an array of values
by broquaint (Abbot) on Jun 28, 2002 at 13:30 UTC
    The problem here is that you're not dereferencing $self correctly and further to that you're not quoting your keys. You probably want something like this
    use Data::Dumper; my $self = {}; @$self{qw/sec min hour mday mon year wday yday isdst/} = localtime(); print Dumper($self); __output__ $VAR1 = { 'isdst' => 0, 'yday' => 178, 'wday' => 5, 'mday' => 28, 'min' => 34, 'year' => 102, 'mon' => 5, 'hour' => 14, 'sec' => 25 };
    Check out perlref and perlreftut for more info about dereferencing.
    HTH

    _________
    broquaint

•Re: adding an array of instance variables and an array of values
by merlyn (Sage) on Jun 28, 2002 at 13:31 UTC
    You can't use an arrow if you're referring to a slice. Time to fall back to the more canonical form of simply replacing the name with a block holding the reference, or just the reference if it's in a simple scalar:
    @$self{qw(sec min hour mday mon year wday yday isdst)} = localtime();

    -- Randal L. Schwartz, Perl hacker

      that's exactly what I wanted ... thanks
Re: adding an array of instance variables and an array of values
by bronto (Priest) on Jun 28, 2002 at 22:03 UTC
    I've a feeling it should be something along the lines of @hash{@keys} = @values; which I've seen on another thread, but I can't quite get there.

    ...but you were near!

    What do you think of:

    sub new { my $class_name = shift; my %self ; @self{qw(sec min hour mday mon year wday yday isdst)} = localtime(); bless \%self,$class_name ; }

    Ciao!
    --bronto

    # Another Perl edition of a song:
    # The End, by The Beatles
    END {
      $you->take($love) eq $you->made($love) ;
    }