in reply to Re: porting C code to Perl
in thread porting C code to Perl

Hello Mr. Muskrat and thanks for your reply,

> Perl's int is not the same as C's floor()..

I already admitted my superb ignorance but i read here that in C floor turns 1.6 1.2 2.8 2.3 into 1 1 2 2 or simply 'This function returns the largest integral value not greater than x'.

This is identical to the int function where any decimal are stripped out: say int $_ for qw(1.6 1.2 2.8 2.3)

> Perl has a pre-decrement just like C..

I have meditated a bit over this before trying to port the code and, sincerely I didnt read the C documents about post and pre increment, but as I have always understood the third part of the Perl's C style for loop is a statement on it's own: ie ++$var; or $var++; are identical.

Infact for($i=0;$i<4;$i++){say $i} and for($i=0;$i<4;++$i){say $i} produce the very same, expectable results. Switching between them in the above code does not change the result.

L*

There are no rules, there are no thumbs..
Reinvent the wheel, then learn The Wheel; may be one day you reinvent one of THE WHEELS.

Replies are listed 'Best First'.
Re^3: porting C code to Perl (updated)
by haukex (Archbishop) on Oct 23, 2017 at 20:08 UTC
    the third part of the Perl's C style for loop is a statement on it's own: ie ++$var; or $var++; are identical.

    Yes, that's correct*, when they're written standalone as in for(;;$var++). ++$var vs. $var++ only makes a difference when its return value is used: ++$var will first increment the variable and then return the new value, while $var++ will return the old value and then increment the variable.

    $ perl -le 'for ( my $x=0; $x<3; print $x++ ) { }' 0 1 2 $ perl -le 'for ( my $x=0; $x<3; print ++$x ) { }' 1 2 3

    * Update: In fact, note what Perl does here (edited for brevity):

    $ perl -MO=Deparse -e 'for ( my $x=0; $x<3; print $x++ ) { }' for (my $x = 0; $x < 3; print $x++) { (); } $ perl -MO=Deparse -e 'for ( my $x=0; $x<3; print ++$x ) { }' for (my $x = 0; $x < 3; print ++$x) { (); } $ perl -MO=Deparse -e 'for ( my $x=0; $x<3; ++$x ) { }' for (my $x = 0; $x < 3; ++$x) { (); } $ perl -MO=Deparse -e 'for ( my $x=0; $x<3; $x++ ) { }' for (my $x = 0; $x < 3; ++$x) { (); }
Re^3: porting C code to Perl
by soonix (Chancellor) on Oct 23, 2017 at 20:31 UTC
    For this particular use case, it doesn't matter, but with negative numbers, int and floor give different results (this is mentioned explicitly in the first link)