in reply to Converting a C structure to Perl

You are making a common c-programmer mistake, one that I regularly made when I started programming in perl. From what I see of your note you equate scalars with strings. This is not the case. Consider the following:

my $a; $a = "Mary had a little lamb"; # $a contains a string $a = 2001; # $a now contains a number $a = '2001'; # $a STILL contains a number $a .= 'AD'; # $a is a string once more :)

How this prints is another matter. print, printf etc all output strings. This is their nature, they know naught else ;). The simplest way to output the byte value of a number is to use the following:

print pack("i", $a);

This will work the same way whiether you represent your data as a number or as a strng of numeric characters; perl interprets both as a number.

print pack("i", 3000); ¨Y¡á print pack("i", '3000'); ¨Y¡á print pack("i", "3000"); ¨Y¡á

Perhaps something like the simple object below will help you

my $data = Data->new("aa", 65, 1.2, "misc", "data string"); print $data->print_secs(); package Data; sub new { my ($class, $id, $secs, $vers, $misc, $data) = @_; my $self = { 'id' => $id, 'secs' => $secs, 'version' => $vers, 'misc' => $misc, 'data' => $data, }; bless $self, $class; return $self; } sub print_secs { # Returns $self->{'secs'} as a byte stream $self = shift; return pack('i', $self->{'secs'}); }

This is a bit crude but perhaps it will give you some ideas.

Replies are listed 'Best First'.
Re: Re: Converting a C structure to Perl
by Fastolfe (Vicar) on Jan 05, 2001 at 19:29 UTC
    I don't tend to use it, but I figure mentioning Class::Struct might be interesting to you guys:
    use Class::Struct; struct data => { id => '$', secs => '$', version => '$', misc => '$', data => '$', next => 'data', # just an example }; $one = new data (id => 1, secs => 2); $two = new data (id => 2, secs => 2, data => 'hi'); $one->next($two); print $one->next->data; # "hi"