LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   Perl experts: what is this code doing? (https://www.linuxquestions.org/questions/programming-9/perl-experts-what-is-this-code-doing-457949/)

bulliver 06-24-2006 04:40 PM

Perl experts: what is this code doing?
 
Hello all,

I have translated a Perl module to Ruby and it went pretty well except for one little bit that I cannot figure out. Here is the Perl code:
Code:

$info{'flags_raw'}                = unpack('V', $self->_readAndIncrementOffset(4));

$info{'flags'}->{'broadcast'}        = ($info{'flags_raw'} & 0x0001) ? 1 : 0;
$info{'flags'}->{'seekable'}        = ($info{'flags_raw'} & 0x0002) ? 1 : 0;

Now on a test run, the value of raw_flags is '2', broadcast is '0', and seekable is '1'.
I have the identical Ruby code:

Code:

flags_raw                  = readAndIncrementOffset(4).unpack("V")[0]
@info['broadcast']          = (flags_raw & 0x0001) ? 1 : 0
@info['seekable']          = (flags_raw & 0x0002) ? 1 : 0

Ruby has a ternary operator too, so this should be identical results but it is not. When I run the Ruby code I get '2' for raw flags, and '1' for both broadcast and seekable.

So: I don't know Perl all that well, but there must be some of that trademark Perl voodoo going one here right? Can anyone tell me why the same operation (ie: a bitwise '&' and a ternary operator) are giving two different results for the same input?

I must admit I do not know much about bitwise operations, so maybe the problem here is differences between how Ruby and Perl evaluate bitwise operations?

Any insight appreciated.

spooon 06-24-2006 07:51 PM

It seems to me that the Perl code does exactly what you expected it to do. It seems that the only difficulty is the Ruby code. From what you have told us, it seems that (2 & 0x0001) evaluates to true in Ruby; is this right? Can you verify this?

bulliver 06-24-2006 08:03 PM

Quote:

It seems that the only difficulty is the Ruby code. From what you have told us, it seems that (2 & 0x0001) evaluates to true in Ruby; is this right? Can you verify this?
Thanks man...

I should have realized: It is evaluating to '0' which in ruby is considered true whereas in Perl it is false.

So simple...


All times are GMT -5. The time now is 09:04 AM.