Re: Problem with anonymous array in hash



Thanks John, sometimes I am too concise with my code and omit things
which should not be omitted, e.g. braces ;-)

John W. Krahn wrote:
bernd wrote:

probably the solution is quite simple, but obviously I am blocked
currently concerning the following:

perl -e '@somearr=split(/ /,"11 12 13"); $hash{'array1'}->[0]=50;
$hash{'array1'}->[2]=100;printf("%d\n", scalar(@somearr));
printf("%d\n",
scalar(@$hash{'array1'}))'

Running this on the command line gives:

3
0

The first number is, as expected, the number of elements in the array
since evaluating an array in scalar context gives it's number of
elements. I would have expected "2" as the outcome for the second,
anonymous array stored in the hash, but obviously I am not referencing
to the array, or?

What am I doing wrong?

If you had enabled warnings perl would have given you a hint:

$ perl -we'
@somearr = ( 11, 12, 13 );
$hash{ array1 }[ 0 ] = 50;
$hash{ array1 }[ 2 ] = 100;
printf "%d\n", scalar @somearr;
printf "%d\n", scalar @$hash{ array1 };
'
3
Use of uninitialized value in printf at -e line 6.
0

The problem is that you are dereferencing $hash when you should be
dereferencing $hash{ array1 } like so:

printf "%d\n", scalar @{ $hash{ array1 } };


perldoc perlref



John
--
use Perl;
program
fulfillment

.



Relevant Pages

  • Making Datatypes Constant and Emulating Const Correctness
    ... Being relatively new to Perl with Java and bits of C under my belt, ... I'm new to C+++, too, but remember a number of uses for the const keyword ... an array to some analizer function as a constant strongly signals that no ... some reference (e,g. a blessed hash reference) ...
    (comp.lang.perl.misc)
  • RE: returning hashes, and arrays
    ... and an array from a different subroutine. ... Must the hash and array really be a reference ... be able to help you get there with perl. ...
    (perl.beginners)
  • FAQ 4.42 How can I tell whether a certain element is contained in a list or array?
    ... comes with the standard Perl distribution. ... How can I tell whether a certain element is contained in a list or array? ... used a hash, not a list or array, to store your data. ... The perlfaq-workers, a group of volunteers, maintain the perlfaq. ...
    (comp.lang.perl.misc)
  • Re: how to pass array and varaible
    ... John and Gunnar, ... > Any arguments passed in show up in the array @_. ... > of Perl created the element whether or not the element was assigned to.) ... > Assigning to the whole array @_ removes that aliasing, ...
    (perl.beginners)
  • Re: script to find most common last names in a file
    ... John W. Krahn wrote: ... > splitreturns a list in list context so you need list context on the ... > splitwill store its results in the @_ array. ... >> # then creat a hash table of first and last names, ...
    (perl.beginners)