in reply to Re^2: arrays of object in OO perl
in thread arrays of object in OO perl

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();

Replies are listed 'Best First'.
Re^4: arrays of object in OO perl
by GrandFather (Saint) on Nov 20, 2008 at 04:34 UTC

    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