in reply to Re: Buffering and output help needed
in thread Buffering and output help needed

Thank you, I know it's ugly, so its good that I can come here and get help :)

Am I better returning values from incStart() pushing them into an array and printing the array?,

And always seperating the print functions from the calculation functions.

$| = 1; my $Qcount = 10; my $Qstart = 0; my $Qint = 3; my @StorageArray; sub incStart { for ( $x = $_[0] ; $x < $_[1] ; $x++ ) { if ( ( $x % $_[2] ) == 0 ) { # print $x . "\n"; # push (@StorageArray, $x); return $x; } } } print "test "; print incStart( $Qstart, $Qcount, $Qint ) . "\n";

This doesnt work either,

Replies are listed 'Best First'.
Re^3: Buffering and output help needed
by Joost (Canon) on Oct 07, 2006 at 13:10 UTC
    A return() statement exits the subroutine. That means you loop won't be completed, since incStart() will stop and return at the first value that matches ( $x % $_[2] ) == 0.

    You'll want to create a list of matching variables to return. You could do it a bit like this: (code clarified a bit)

    use strict; use warnings; sub incStart { my ($start,$end,$mod) = @_; my @result; for ( my $x = $start ; $x < $end ; $x++ ) { if ( ( $x % $mod ) == 0 ) { push @result,$x; # append $x to result list } } return @result; # <- return AFTER completing the loop } print "test "; foreach my $result (incStart(0,10,3)) { print "$result\n"; }

    Please also be very careful about where you define variables and use strict and warnings.

      You are right, i needed to local scope the varibles in the sub routine, name them more clearly.

      I'd remembered about return exiting the sub routine and just finshed altering my code so that it worked like yours but with poor varible scoping and naming.

      It was good to see the difference.