in reply to arrays of object in OO perl

Would you mind if I say a small change?

This is c-style looping

for ($i=0; $i<5; $i++) {

should be as

foreach my $i ( 0 .. 4 ) {

Replies are listed 'Best First'.
Re^2: arrays of object in OO perl
by GrandFather (Saint) on Nov 19, 2008 at 08:49 UTC

    The counter isn't used so the range is better expressed 1 .. 5.


    Perl reduces RSI - it saves typing
      Actually it is used, to indicate/display the running number. So, the counter is needed

      push (@{$this->{individual}}, $empl); print " ".$i."\n"; print $this->{individual}->[$i]->getDNA();

        so given the number is shown in the UI the range should be from 1, although it would then need to be adjusted for the array index (if you need to use it as such). There are a number of things in that code fragment that can be tidied up somewhat. Consider:

        for my $i (1 .. 5) { my $empl = Animal->new(); push @{$this->{individual}}, $empl; print " $i\n"; print $empl->getDNA (); }

        push doesn't need () and there is less clutter on the line without them. $i can be interpolated directly into the string again reducing clutter. Using $empl makes it clear that that is the object being accessed rather than figuring out that that was the last thing pushed onto the array and that the index variable is correct. Instead of the index you could have written:

        print $this->{individual}[-1]->getDNA();

        which gets you the last element in the array and is safer than relying on the index variable being correct, but doesn't make the intent as clear as using the variable as shown earlier.


        Perl reduces RSI - it saves typing