Sunday, September 10, 2006

Perl: Creating empty arrays and hashes

Using arrays and hashes in Perl is essential. Nevertheless Perl way of handling those data types is more difficult; by comparison with, for example Ruby or Python. Now I am not going to focus on all aspects of arrays and hashes in Perl, because this topic is just to big for one post. Today, I will describe funny problem that my co-worker had, or rather his little bug in his program.

The problem was with deleting or emptying and array or hash.
For example, let assume that we have one array @a, and one hash %h:

my @a = ( 2, 3, 4);
my %h = ('me'=>2, 'you'=>3, 'he',=>'4');

print 'Size of @a: ', scalar @a; #gives 3
print 'Size of %h: ', scalar keys %h; #gives 3

Now, we want to delete its content. What my friend did, was:

@a=[]; #WRONG: should be @a=();
%h={}; #WRONG: should be %h=();

print 'Size of @a: ', scalar @a; #gives 1 !!!
print 'Size of %h: ', scalar keys %h; #gives 1 !!!

This little mistake cost him a lot of hours of looking for bug in his code. What he did, he created anonymous empty array [] and anonymous empty hash {} and assign them as first element in $a[0] and as first key in %b.

Hence, the correct code to empty an array or a hash is:


print 'Size of @a: ', scalar @a; #gives 0 !!!
print 'Size of %h: ', scalar keys %h; #gives 0 !!!

1 comment:

  1. Perl online training|Perl training|call us+919000444287 ...
    Perl Online Training, Perl Scripting online training by real time Experts from Hyderabad, India. Call 9000444287 for online training demo. Online Perl training ...