Convert a Perl code to PHP

前端 未结 8 1578
粉色の甜心
粉色の甜心 2021-01-29 08:50

I need to convert the following perl function to php:

pack(\"SSA12AC4L\",
     $id,
     $loc,
     $name,
     \'ar\',
     split(/\\./, $get->getIP),
     t         


        
8条回答
  •  独厮守ぢ
    2021-01-29 09:45

    My first suggestion is that you carefully read the documentation. This problem has little to do with perl and much to do with understanding what the function expects. My second suggestion is to get in the habit of feeling a little nervous whenever you copy some code. Nervous enough to pay extra attention to the code, the documentation, etc. At the very least, when a client/boss/whoever asks you what that bit of copied code does, you should have a good answer.

    The first parameter to pack() is a format string. This determines how it formats the parameters when it creates the output.

    From the documentation for pack():

    The format string consists of format codes followed by an optional repeater argument. The repeater argument can be either an integer value or * for repeating to the end of the input data. For a, A, h, H the repeat count specifies how many characters of one data argument are taken, for @ it is the absolute position where to put the next data, for everything else the repeat count specifies how many data arguments are consumed and packed into the resulting binary string.

    So, the problem is that your format string isn't appropriate for the arguments you pass to pack(). Now, keep in mind that I have to guess at the appropriate format string for your needs. You have to read the documentation and determine the correct format string.

    The following works just fine:

    echo pack("SSA12ACL",
    '25',
    '00001',
    '2u7wx6fd94fd',
    'f',
    preg_split('/\./','10.2.1.1', -1, PREG_SPLIT_NO_EMPTY),
    '1278761963');
    

    The function preg_split() returns a single array. However, the 'C4' in the original format string expects to take in 4 parameters. Based on my count, the original format string implied 9 parameters, not 6.

提交回复
热议问题