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

Desperate of your wisdom:

I have en excerpt of C code:
strcat(cc,"\015"); index=strlen(cc); memset(&cmd,0,sizeof(cmd)); memcpy(&cmd,&index,sizeof(int)); memcpy((cmd+4),&cc,index);
Could anyone help me with getting the equivalent in perl?

Thanks in advance,

Pete

edited: Wed Apr 16 17:05:30 2003 by jeffa - code tags, removed br tags

Replies are listed 'Best First'.
Re: C to Perl
by tall_man (Parson) on Apr 04, 2003 at 22:31 UTC
    Here is a start. Depending on the size of cmd, you can adjust the padding of the Z part.
    use strict; my $cc = "whatever"; # Pack a length and the cc string into a cmd field. $cc .= "\015"; my $index = length($cc); my $cmd = pack 'iZ10',$index,$cc;
      tall man writes:
      Here is a start. Depending on the size of cmd, you can adjust the padding of the Z part.
      use strict; my $cc = "whatever"; # Pack a length and the cc string into a cmd field. $cc .= "\015"; my $index = length($cc); my $cmd = pack 'iZ10',$index,$cc;
      You can use Z* instead of Z10, so you don't have to change the number. Strictly speaking it would be better to "A" instead of "Z" since the original doesn't include the "\0", but it won't really matter since the length at the beginning doesn't include it either. There's also a bit of a short cut in recent Perl's (5.6 and later, I think):
      $cc .= "\015"; my $cmd = pack "i/A*", $cc;
      which automatically takes the length for the integer.
        You can use Z* instead of Z10

        I disagree, because the original code fills cmd with null bytes first before filling in the size and the string. To get the same effect we need a null-padded string in the pack.

        I imagine this code to be part of a symbol table with fixed-length cmd records, so the exact size could matter.

Re: C to Perl
by dmitri (Priest) on Apr 04, 2003 at 21:58 UTC
    Your C code seems to be wrong:
    memcpy(&cmd,&index,sizeof(int)); memcpy((cmd+4),&cc,index);
    Is cmd a pointer or not? Also, I suggest giving us some types here.
Re: C to Perl
by vivapl (Acolyte) on Apr 07, 2003 at 16:27 UTC
    This piece of code is actualy to build a packet to be sent to a server. How would I approach padding out cmd with zero's
      There are several ways to null-pad using pack. You could use "Z" format as I suggested above, or "x" to put in a specific number of null bytes, or "@" to null-fill to a specific position. The documentation for pack can be found using:
      perldoc -f pack