http://www.perlmonks.org?node_id=640274

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

There are two code snippets pasted below for pragma constant. First program works fine. And second seems not working. Pour your Ideas.

First Program below :

#!/usr/local/bin/perl use strict; use warnings; use Data::Dumper; my %hash = ( 'a' => 2 ); use constant A => \%hash; print A->{a};

Second Program below :

#!/usr/local/bin/perl use strict; use warnings; use Data::Dumper; my $hash = { 'a' => 2 }; use constant A => $hash; print A->{a};

Gubs

Nice to Breathe with Perl :-) Just try

Replies are listed 'Best First'.
Re: Doubt in assigning hash reference values for Constant pragma declaration ?
by salva (Canon) on Sep 21, 2007 at 07:08 UTC
    use constant A => $hash;
    is evaluated at compilation time, before
    my $hash = { 'a' => 2 };
    has been executed.

    Yo can use a BEGIN block to make the assignment at compile time:

    my $hash; BEGIN { $hash = { 'a' => 2 } } use constant A => $hash;
    Or also:
    my $hash; use constant A => $hash = {'a' => 2};

      The above given information and example was very nice.

      Thanks
      Gubs

Re: Doubt in assigning hash reference values for Constant pragma declaration ?
by Anonymous Monk on Sep 21, 2007 at 07:03 UTC
    The assignment my $hash = { 'a' => 2 }; is wrong way of initilising the hash and my %hash = ( 'a' => 2 ); is the right way thats why it dosent work

      The first example initializes a hash reference. What's wrong with that, or are you just objecting to the terms?