Search code examples
phpperlpack

Convert a Perl code to PHP


I need to convert the following perl function to php:

pack("SSA12AC4L",
     $id,
     $loc,
     $name,
     'ar',
     split(/\./, $get->getIP),
     time+(60*60);

I use the following code (to test) in PHP:

echo pack("SSA12AC4L",
     '25',
     '00001',
     '2u7wx6fd94fd',
     'f',
     preg_split('/\./','10.2.1.1', -1, PREG_SPLIT_NO_EMPTY),
     time()+(60*60));

But I'm getting the following error: Warning: pack() [function.pack]: Type C: too few arguments in D:\wamp\www\test.php on line 8

Any suggestions? Thanks a lot.


Solution

  • The problem is that the code is giving to pack() (I am referring the the last arguments) a character, an array, and an integer. As the code C wants 4 characters, that is the cause of the error.

    The code should be something like

    $split = preg_split('/\./','10.2.1.1', -1, PREG_SPLIT_NO_EMPTY);
    echo pack("SSA12AC4L",
      '25',
      '00001',
      '2u7wx6fd94fd',
      'f',
      $split[0],
      $split[1],
      $split[2],
      $split[3],
      time()+60*60
    );
    

    Then, there is no reason to use preg_split() in this case, when explode() can be used instead. Regular expressions should be used only when strictly necessary because the regular expression functions are slower, compared to other string functions.