Difference between accessing arrays and associative arrays using a int index

Discussion in 'Perl Misc' started by shashi, Apr 12, 2006.

  1. shashi

    shashi Guest

    Hi,

    Recently a friend of mine asked me this question. I know the
    difference between the normal arrays and associative arrays. But i
    want to know whether can i use an integer as key in the associative
    arrays?. If so, what is the difference between accessing the first
    element of an array as a[1] and accessing a associative array b
    with key 1 as b{1} ?

    Regards,
    Shashi.
    shashi, Apr 12, 2006
    #1
    1. Advertising

  2. Re: Difference between accessing arrays and associative arrays usinga int index

    shashi wrote:
    >
    > Recently a friend of mine asked me this question. I know the
    > difference between the normal arrays and associative arrays. But i
    > want to know whether can i use an integer as key in the associative
    > arrays?.


    Yes.

    > If so, what is the difference between accessing the first
    > element of an array as a[1] and accessing a associative array b
    > with key 1 as b{1} ?


    You probably meant $a[1] and $b{1} and the first element of an array is in
    $a[0] and a hash does not have a "first" element. Aside from that there
    should be little difference accessing a single element from either.


    John
    --
    use Perl;
    program
    fulfillment
    John W. Krahn, Apr 12, 2006
    #2
    1. Advertising

  3. shashi

    shashi Guest

    Sorry John,

    i meant is $a[1] and $b{2}. When i say $b{1} does it go directly
    to the concerned element to pick up the value as in $a[1] or not or we
    need to calculate the hash for finding the concerned integer key in
    $b{1}.

    If u do not understand the question, please tell me how program
    access the normal array and associative array


    Regards,
    Shashi.
    shashi, Apr 12, 2006
    #3
  4. shashi

    Guest Guest

    shashi <> wrote:
    : Hi,

    : Recently a friend of mine asked me this question. I know the
    : difference between the normal arrays and associative arrays. But i
    : want to know whether can i use an integer as key in the associative
    : arrays?. If so, what is the difference between accessing the first
    : element of an array as a[1] and accessing a associative array b
    : with key 1 as b{1} ?

    Hi Shashi,

    Please read a bit of the following lines before your question gets answered!

    Under any circumstances you can answer parts of your question by writing
    a few lines of code using the variables which you want to explore. Make
    sure you start your script with the lines

    use warnings;
    use strict;

    and you'll immediately notice that you should declare your variables and
    start them with the indicator for scalars, a dollar sign. While Perl allows
    bare words under certain conditions, I rather suggest not to stretch this
    feature as it will only cause confusion if you do not know where to look
    for the origin of potential problems. So, $scalar is better than scalar, and
    beginning with "my $scalar" is even better.

    Then, you should always avoid to call your variables $a or $b; Perl has
    internal variables of the same name that can be user-manipulated. When-
    ever your sort or comparison operation goofs then most certainly due
    to indiscriminate use of $a and $b elsewhere in the program.

    In addition, did you declare "$[=1;" anywhere in your script prior to
    writing "$a[1]"? Most probably, you didn't do so, and hence the first
    element of an array is reached by the index [0], not [1]. The index
    number in square brackets indicates the _offset_ of the array slice,
    not the _ordinal count_ of the array slice. Your $a[1] really indicates
    the second element in your array @a. You can set the offset with $[
    so that Perl behaves a bit more like awk (see the perlvar manpage);
    while this may feel more *natural* to some, it runs across general
    expectations and usage.

    Now to your question: What is the difference between $value[1] and
    $value{1}? In casual use, you won't find any difference, but...

    a) Order

    Arrays are ordered.

    You can always be sure that the element after $value[1] is found
    by saying $value[2].

    There is no guarantee whatsoever that you can address two consecutive
    elements of a hash by saying $hashvalue{1} and then $hashvalue{2}.

    Which means: if you want to retrieve the values of a hash in ordered
    manner, you have to sort the keys first. Study perlfunc and
    perldoc -f keys. You will note that virtually all code iterating over
    hash values has a line that starts with:

    foreach $element (sort keys %myhash) {
    ...
    }


    b) Slices

    You can "cut" slices out of an array by saying @dayofweek[3,4,5] which
    will return a list with three elements; similar things are possible
    with a hash. Again, see man perldata.


    c) Special values

    You can find the last element of an array by using the $#array notation;
    you can't do so with a hash because a hash is not ordered. There is only
    a most recently inserted element, but no last element.

    Beyond these, there are certainly more intricate and subtle differences.

    It is also good to have a look at the posting guidelines which are posted
    here regularly. Conforming with this will substantially increase the feed-
    back to your postings.

    Oliver.


    --
    Dr. Oliver Corff e-mail: -berlin.de
    Guest, Apr 12, 2006
    #4
  5. shashi

    shashi Guest

    Thanks Oliver for the reply. I am a bit hurry with my work. So i
    couldn't follows the above said guidelines. I will make sure that they
    will be followed in my next posts.
    shashi, Apr 12, 2006
    #5
  6. shashi

    Bart Lateur Guest

    shashi wrote:

    >I know the
    >difference between the normal arrays and associative arrays. But i
    >want to know whether can i use an integer as key in the associative
    >arrays?.


    Yes, of course. Any string can be used as a key of an associative array
    (AKA hash), and an integer is no exception. It'll be converted to a
    string, first.

    > If so, what is the difference between accessing the first
    >element of an array as a[1] and accessing a associative array b
    >with key 1 as b{1} ?


    Two differences:

    1) The hash will be a "sparse array": only the items that get addressed,
    will exist. If you create a hash item $a{1234567}, then there'll be only
    one item added. If you create an array item $a[1234567], then over 1
    million items will be created.

    2) You must take care that you only use the characters that you want. If
    necessary, add 0 to the value before using it as a key. $a[123] and
    $a[" 123"] have the same value as an index, but $a{123} and $a{" 123"}
    do not.

    Oh, and those hash keys are in as-good-as-random order, as always.

    --
    Bart.
    Bart Lateur, Apr 12, 2006
    #6
  7. shashi wrote:
    > Recently a friend of mine asked me this question. I know the
    > difference between the normal arrays and associative arrays. But i
    > want to know whether can i use an integer as key in the associative
    > arrays?.


    Absolutely. Why not?
    Conceptionally arrays are a mapping from natural numbers to scalars while
    hashes are a generalization that maps arbitrary strings to scalars.


    > If so, what is the difference between accessing the first
    > element of an array as a[1] and accessing a associative array
    > b with key 1 as b{1} ?


    In practical terms almost none:
    - the key will be the string value of the integer, not the numerical value.
    That shouldn't matter.
    - the array will contain 2 elements while the hash contains only 1. This
    becomes significant if you are considering $arr[500000] versus
    $hash{'500000'}
    - and of course hashes are not ordered

    jue
    Jürgen Exner, Apr 12, 2006
    #7
  8. "shashi" <> wrote in
    news::

    > Thanks Oliver for the reply. I am a bit hurry with my work. So i
    > couldn't follows the above said guidelines. I will make sure that they
    > will be followed in my next posts.


    This is your "next post" and you are still not following them.

    Sinan

    --
    A. Sinan Unur <>
    (remove .invalid and reverse each component for email address)

    comp.lang.perl.misc guidelines on the WWW:
    http://augustmail.com/~tadmc/clpmisc/clpmisc_guidelines.html
    A. Sinan Unur, Apr 12, 2006
    #8
  9. shashi

    Dr.Ruud Guest

    shashi schreef:
    > Hi,
    >
    > Recently a friend of mine asked me this question. I know the
    > difference between the normal arrays and associative arrays. But i
    > want to know whether can i use an integer as key in the associative
    > arrays?. If so, what is the difference between accessing the first
    > element of an array as a[1] and accessing a associative array
    > b with key 1 as b{1} ?


    As a side note, you could maintain an array parallel to a hash, or v.v.

    #!/usr/bin/perl
    use strict;
    use warnings;

    local ($", $\) = ("\n", "\n");

    my @a = (0, 1, 3, 4, 7, 8, 999 );

    my %b =
    ( 'very first' => \$a[0]
    , 'first' => \$a[1]
    , 'second' => \$a[2]
    , 'third' => \$a[3]
    , 'last' => \$a[$#a]
    );

    push @a, '---';
    print "@a";

    (${$b{'third'}} *= 10) += 9;
    print "@a";

    my @b;
    for (sort keys %b) { push @b, "$_:\t${$b{$_}}" }
    print "@b";
    __END__

    Is there a nicer way to write those ${$b{<key>}}-s?

    --
    Affijn, Ruud

    "Gewoon is een tijger."
    Dr.Ruud, Apr 12, 2006
    #9
  10. shashi

    shashi Guest

    Hi sorry guys,

    i just got sometime to write the question clearly. This is an
    interview question with google. They asked me why you use b{0} instead
    of a[0]. where a is a normal array and b is an associative array with
    the key as an integer. I mean from the performance point of view, why
    would you prefer using an associative array than a normal one, even
    when the key of the array is an integer.


    Regards,
    Shashi.
    shashi, Apr 12, 2006
    #10
  11. shashi

    Dr.Ruud Guest

    shashi schreef:

    > They asked me why [would] you use b{0} instead
    > of a[0]. where a is a normal array[,] and b is an associative
    > array with the key [supplied] as an integer.


    See my [correction]s.

    One answer: with sparse arrays.

    --
    Affijn, Ruud

    "Gewoon is een tijger."
    Dr.Ruud, Apr 12, 2006
    #11
  12. "shashi" <> wrote in
    news::

    > Hi sorry guys,


    Sorry for what?

    > i just got sometime to write the question clearly. This is an
    > interview question with google. They asked me why you use b{0} instead
    > of a[0].


    Both of those are syntax errors.

    I think it is safe to assume that you understand neither the question nor
    Perl. Do you think that we will help you get a job when you can't even
    phrase the question in terms others can understand.


    Sinan
    A. Sinan Unur, Apr 12, 2006
    #12
  13. shashi

    Guest

    "shashi" <> wrote:
    > Sorry John,
    >
    > i meant is $a[1] and $b{2}. When i say $b{1} does it go directly
    > to the concerned element to pick up the value as in $a[1] or not


    Perl never* does anything directly. It uses umpteen layers of indirection.

    > or we
    > need to calculate the hash for finding the concerned integer key in
    > $b{1}.


    Well, surely *you* do not need to calculate the hash. Perl does that for
    you.

    Xho

    * never say never.

    --
    -------------------- http://NewsReader.Com/ --------------------
    Usenet Newsgroup Service $9.95/Month 30GB
    , Apr 12, 2006
    #13
  14. shashi

    Anno Siegel Guest

    Dr.Ruud <> wrote in comp.lang.perl.misc:
    > shashi schreef:
    > > Hi,
    > >
    > > Recently a friend of mine asked me this question. I know the
    > > difference between the normal arrays and associative arrays. But i
    > > want to know whether can i use an integer as key in the associative
    > > arrays?. If so, what is the difference between accessing the first
    > > element of an array as a[1] and accessing a associative array
    > > b with key 1 as b{1} ?

    >
    > As a side note, you could maintain an array parallel to a hash, or v.v.
    >
    > #!/usr/bin/perl
    > use strict;
    > use warnings;
    >
    > local ($", $\) = ("\n", "\n");
    >
    > my @a = (0, 1, 3, 4, 7, 8, 999 );
    >
    > my %b =
    > ( 'very first' => \$a[0]
    > , 'first' => \$a[1]
    > , 'second' => \$a[2]
    > , 'third' => \$a[3]
    > , 'last' => \$a[$#a]
    > );
    >
    > push @a, '---';
    > print "@a";
    >
    > (${$b{'third'}} *= 10) += 9;
    > print "@a";
    >
    > my @b;
    > for (sort keys %b) { push @b, "$_:\t${$b{$_}}" }
    > print "@b";
    > __END__
    >
    > Is there a nicer way to write those ${$b{<key>}}-s?


    Not really.

    The setup of %b can be made more compact, using the fact that reference-taking
    "\" distributes over lists:

    my %b;
    @b{ 'very first', qw( first second third last)} = \ @a[ 0 .. 3, -1];

    Anno
    --
    If you want to post a followup via groups.google.com, don't use
    the broken "Reply" link at the bottom of the article. Click on
    "show options" at the top of the article, then click on the
    "Reply" at the bottom of the article headers.
    Anno Siegel, Apr 12, 2006
    #14
  15. shashi <> wrote:

    > But i
    > want to know whether can i use an integer as key in the associative
    > arrays?.



    What happened when you tried it?


    --
    Tad McClellan SGML consulting
    Perl programming
    Fort Worth, Texas
    Tad McClellan, Apr 12, 2006
    #15
  16. shashi

    Paul Lalli Guest

    Ferry Bolhar wrote:
    > Oliver:
    >
    > > Then, you should always avoid to call your variables $a or $b; Perl has
    > > internal variables of the same name that can be user-manipulated.

    >
    > These aren't special variables as long as sort {...} isn't used.


    Yes they are.

    $ perl -Mstrict -e'
    my $a1 = "foobar\n";
    print $a; #oops
    '

    No errors. Just nothing printed. Because $main::a and $main::b are
    exempt from strict 'vars'. Now, if you enable warnings, you will get
    the "main::a used only once" warning, and another for printing an
    uninitialized value. But they are most definately "special".

    Paul Lalli
    Paul Lalli, Apr 13, 2006
    #16
  17. shashi

    Guest Guest

    Ferry Bolhar <> wrote:
    : Oliver:

    : > Then, you should always avoid to call your variables $a or $b; Perl has

    : These aren't special variables as long as sort {...} isn't used. And even
    : within a block passed to sort, $a and $b are local-ized therein, and you
    : can use them elsewhere in a program as much as you want.

    That's absolutely correct, and I was aware of this at the time of writing;
    however, taking the OP's apparent knowledge depth of Perl into account, I
    deemed it better to raise the attention in a general manner. I didn't want
    to complicate things further.

    : And the op wrote about $a[1} and $b{1}, therefore about elements
    : of an array @a and a hash %b which have nothing to do with scalars
    : $a and $b.

    Of course this is self-understood, too. However, the OP didn't even use
    the '$' (dollar) sign to indicate the scalar, and I wanted to point out
    just this. The perldata manpage has it all, but perhaps I overshot a little.

    Oliver.


    --
    Dr. Oliver Corff e-mail: -berlin.de
    Guest, Apr 13, 2006
    #17
  18. shashi

    Guest Guest

    -berlin.de wrote:

    : : These aren't special variables as long as sort {...} isn't used. And even
    : : within a block passed to sort, $a and $b are local-ized therein, and you
    : : can use them elsewhere in a program as much as you want.

    : That's absolutely correct, and I was aware of this at the time of writing;
    : however, taking the OP's apparent knowledge depth of Perl into account, I
    : deemed it better to raise the attention in a general manner. I didn't want
    : to complicate things further.

    I mentioned sorting in my original posting, though.

    Oliver.

    : --
    : Dr. Oliver Corff e-mail: -berlin.de

    --
    Dr. Oliver Corff e-mail: -berlin.de
    Guest, Apr 13, 2006
    #18
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. jakk
    Replies:
    4
    Views:
    12,047
  2. Schnoffos
    Replies:
    2
    Views:
    1,198
    Martien Verbruggen
    Jun 27, 2003
  3. Hal Styli
    Replies:
    14
    Views:
    1,615
    Old Wolf
    Jan 20, 2004
  4. arun
    Replies:
    8
    Views:
    433
    Dave Thompson
    Jul 31, 2006
  5. desktop
    Replies:
    5
    Views:
    376
    James Kanze
    Jun 26, 2007
Loading...

Share This Page