in reply to Please Explain this Function

The function returns a formated string with 3 components joined with no token together. The components are 'packed' in to a string
OK so...
my $msg = pack("a".$maxMsgCodeLength."ia*",$msgCode, $port, $ip);
"StartBE" is 7 characters long, this gets postfixed with spaces by
  $msgCode = $msgCode.(" " x ($maxMsgCodeLength-length($msgCode))); We'll say the max length is 10 here to make it easier.
"StartBE   " is now our string.
my $msg = pack( "a10ia*", $msgCode, $port, $ip );
Can be written more clearly as
my $msg = pack( "a20 i a*", $msgCode, $port, $ip );
From pack on perldoc:
a = A string with arbitrary binary data, will be null padded.
i = A signed integer value.

The three arguments ( $msgCode, $port, $ip ) get 'packed' into ( a10, i and a* ) respectively.

10 Number of characters in first arugment
* However many items are left

If you're familar with printf then it's simlar (but more powerfull then that )
printf( "%s %d %s", $msgCode, $port, $ip );




You could use 'A' instead of 'a' in the pack statement. This will pad with spaces hence if you set A20 and only give a string length 10 then 10 spaces are added to the end rendering the line previous to pack useless. You'd probably want to make the function more generic...
print getMessage ( 'StartBE', $ip, $port ), "\n"; sub getMessage { my ( $msgCode, $ip, $port) = @_; return pack "A10 i A*", $msgCode, $port, $ip; }


J,

Replies are listed 'Best First'.
Re^2: Please Explain this Function
by koti688 (Sexton) on May 15, 2009 at 13:12 UTC
    Thanks a Lot , binf-jw This helps me a lot with your clear explanation