wannabeboy has asked for the wisdom of the Perl Monks concerning the following question:

Hi,
How do I get the first integer that follows, in such orperation (I mean I want to truncate):
15/2??

say it's 7.5, I want 8!

thanks

janitored by ybiC: Retitle from hinders-site-search-results one-word "operators"

Replies are listed 'Best First'.
Re: integer operations
by Thilosophy (Curate) on Mar 01, 2005 at 09:49 UTC
    Try ceil in the POSIX module:
    use POSIX qw(ceil); print ceil (15/2);
    For positive numbers int(15/2) + 1 probably also works, but the docs for int discourage this use.

    Update: Actually, int(15/2) + 1 will not work very well at all, because int(14/2)+1 also produces 8, whereas you want 7 (I guess). Sorry to have brought it up...

Re: integer operations
by Jasper (Chaplain) on Mar 01, 2005 at 10:23 UTC
Re: integer operations
by ambrus (Abbot) on Mar 01, 2005 at 18:58 UTC
    POSIX::ceil is the solution, but if you know that the numerator is always an integer, and the denominator is a positive integer, then you can use this too:
    $numerator = 15; $denominator = 2; print int(($numerator $denominator + - 1) / $denominator), $/;
    or
    $numerator = 15; $denominator = 2; print do{ use integer; ($numerator ++ $denominator - 1) / $denominator }, $/;
Re: integer operations
by DrHyde (Prior) on Mar 01, 2005 at 10:09 UTC
    There's also the integer pragma. You don't want it in this case because it will throw away the 0.5 giving you 7, but I expect some other monks looking at this will find it useful:
    $ perl -Minteger -e 'print 15/2' 7
      obvious but...
      perl -Minteger -e 'print 15/2 + 1'
      prints 8... or
      use strict; use warnings; my $eight = int (15 / 2 ) +1; print $eight;
        Untested:
        my @integers = 1..50000; print $integer[15/2];

        Yes, I'm just being silly. Also, this won't work for negative numbers. At all.
Re: integer operations
by Roy Johnson (Monsignor) on Mar 01, 2005 at 14:14 UTC
    Here's a little ceiling function, if you don't feel like using POSIX:
    sub ceil { my $n = shift; int($n) + ($n > int($n)); }

    Caution: Contents may have been coded under pressure.
      Why would anyone not want to use POSIX? It's a core module, and is damned useful. It's also woefully underused.
        Indeed. Writing your own is more typing, and it's slower as well. About the only reason I can think of is wanting to avoid the loading of POSIX. But if that's significant, you probably want to inline your ceiling functionality anyway.
        #!/usr/bin/perl use strict; use warnings; use POSIX 'ceil'; use Benchmark 'cmpthese'; sub my_ceil { my $n = shift; int($n) + ($n > int($n)) } our @tries = map {-100 + rand 50} 1 .. 1_000; cmpthese -1, { ceil => '@a = map { ceil($_)} @tries', own => '@b = map {my_ceil($_)} @tries', inline => '@c = map {int($_) + ($_ > int($_))} @tries', }; __END__ Rate own ceil inline own 355/s -- -52% -54% ceil 737/s 107% -- -4% inline 767/s 116% 4% --