user2036212
user2036212

Reputation: 37

Perl using hash during declaration

I'd like to have all the items in cflags automatically in cppflags. How do I? Following fail code:

my %conf = (
    'cflags'   => ['-g', '-O0'],
    'cppflags' => [ @{$conf{cflags}} ],
    'bindir'   => $PWD . "/bin",
);

Sorry for the silly question, I'm new to perl :P.

Upvotes: 1

Views: 78

Answers (2)

Joel Berger
Joel Berger

Reputation: 20280

To follow up on ikegami's answer, here is one other suggestion that has a slightly different use case:

my @cflags = qw( -g -O0 );
my %conf = (
    cflags   => \@cflags,
    cppflags => \@cflags,
    bindir   => "$PWD/bin",
);

This is different that his #1 because the @cflags array and the values of the keys cflags and cppflags are all related to the same array. Change any one of them and the others will reflect the change. Perhaps this is the behavior what you want, or perhaps its not, or maybe it makes no difference to you, but there it is.

Upvotes: 1

ikegami
ikegami

Reputation: 386541

You're still building the list to assign to %conf, so nothing's been assigned to %conf yet, so trying to read from $conf{cflags} is going to be fruitless.

Option 1:

my @cflags = qw( -g -O0 );
my %conf = (
    cflags   => [ @cflags ],
    cppflags => [ @cflags ],
    bindir   => "$PWD/bin",
);

Option 2:

my %conf;
$conf{cflags  } = [qw( -g -O0 )];
$conf{cppflags} = [ @{ $conf{cflags} } ];
$conf{bindir  } = "$PWD/bin";

Option 3:

my %conf = (
    cflags => [qw( -g -O0 )],
    bindir => "$PWD/bin",
);
$conf{cppflags} = [ @{ $conf{cflags} } ];

(In decreasing order of personal preference.)

Upvotes: 3

Related Questions