Difference between accessing arrays and associative arrays using a int index

S

shashi

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.
 
J

John W. Krahn

shashi said:
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
 
S

shashi

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.
 
G

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} ?

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.
 
S

shashi

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.
 
B

Bart Lateur

shashi said:
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.
 
J

Jürgen Exner

shashi said:
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
 
A

A. Sinan Unur

D

Dr.Ruud

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?
 
S

shashi

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.
 
D

Dr.Ruud

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.
 
A

A. Sinan Unur

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
 
X

xhoster

shashi said:
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.
 
A

Anno Siegel

Dr.Ruud said:
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
 
P

Paul Lalli

Ferry said:
Oliver:


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
 
G

Guest

: 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.
 
G

Guest

(e-mail address removed)-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: (e-mail address removed)-berlin.de
 

Ask a Question

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

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,733
Messages
2,569,440
Members
44,832
Latest member
GlennSmall

Latest Threads

Top