in reply to Re: condensing code
in thread condensing code

That was my initial thought but that would make 30 => 2 and not 1. So I think he wants int( ($num-1) / 30 ) + 1.

#!/usr/bin/perl use strict; use warnings; my @nums = ( 1 .. 1000 ); foreach my $num ( @nums ) { my $test_n = int( ($num-1) / 30 ) + 1; print "Num: $num - $test_n \n"; }

-derby

Replies are listed 'Best First'.
Re^3: condensing code
by ptum (Priest) on Sep 08, 2006 at 18:02 UTC

    Um, technically this won't work either for $total_nums = 1, much as friedo's version doesn't work for $total_nums values of 30, 60, 90, etc., based on the OP's original code. Looks like diotalevi's example using ceil() is better.

    Update: Ah, I see you updated your version to add 1 after getting the int() value. Fine.

    (Blush)Another Update: Uh, actually, not fine. Now yours doesn't work for values of 31, 61, etc.

      Wha??? Sure it does 31 => 2 and 61 => 3 just like the OP:

      $ perl -e 'print int( (31-1) / 30 ) + 1, "\n"' 2 $ perl -e 'print int( (61-1) / 30 ) + 1, "\n"' 3

      -derby

        Sorry. I got a little overzealous 'correcting' you. You're right ... I need to slow down a little before posting. :)