[prog] quick perl question
Caroline Johnston
johnston at biochemistry.ucl.ac.uk
Thu Mar 4 18:18:45 EST 2004
Many thanks.
Is it ok to declare a variable in a loop? Does it get binned at the end
and recreated at the start of every loop? Does it matter if it does?
Cxx
On Fri, 5 Mar 2004, Jacinta Richardson wrote:
>
> On Thu, 4 Mar 2004, Caroline Johnston wrote:
>
> > {
> > my $rowlength = 0;
> > my $pos= 0;
> > foreach my $row (@rows)
> > {
> > next if $row =~ /^\s$/;
> > push @matrix, [split /$delim/, $row];
> > $rowlength = @{@matrix[$pos]} if ($rowlength == 0);
> > die("different row lengths in data matrix") unless ($rowlength == @{@matrix[$pos]})
> >
> > }
> > }
> >
> > does that look OK? Better to use a for loop?
>
> Nah. Just changing one variable you avoid needing to know where you are
> in the list at all.
>
>
> > {
> > my $rowlength = 0;
> > foreach my $row (@rows)
> > {
> > next if $row =~ /^\s$/;
> my @split = split /$delim/, $row];
> > push @matrix, [@split];
> > $rowlength = @split if ($rowlength == 0);
> > die("different row lengths in data matrix") unless ($rowlength == @split})
> >
> > }
> > }
>
> Of course, there's more than one way to do it, and if you're someone who
> really, really doesn't like extra variables hanging around, you might
> prefer this answer: (I prefer the former because it's more clear, but
> not by much)
>
> > {
> > my $rowlength = 0;
> > foreach my $row (@rows)
> > {
> > next if $row =~ /^\s$/;
> > push @matrix, [split /$delim/, $row];
> > $rowlength = @{@matrix[-1]} if ($rowlength == 0);
> > die("different row lengths in data matrix") unless ($rowlength == @{@matrix[-1]})
> >
> > }
> > }
>
> That's right. Perl lets you count backwards through your arrays too.
> -1 is the last entry, -2 is the second last entry and so forth.
> (- at array) should give you position 0. :)
>
> > numify? really? Fantastic word!
>
> Yup. It goes next to stringify. Which is what happens when you treat a
> scalar as a string.
>
> I hope this helps,
>
> Jacinta
>
> --
> ("`-''-/").___..--''"`-._ | Jacinta Richardson |
> `6_ 6 ) `-. ( ).`-.__.`) | Perl Training Australia |
> (_Y_.)' ._ ) `._ `. ``-..-' | +613 9354 6001 |
> _..`--'_..-_/ /--'_.' ,' | contact at perltraining.com.au |
> (il),-'' (li),' ((!.-' | www.perltraining.com.au |
>
More information about the Programming
mailing list