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.
From the PHP documentation for pack().
Surely it should just work as is? You may need to rename some variables
Sometimes the error statements mean something worth reviewing. Too few arguments may mean there is a need to review each input used in the PHP pack statement aligns with the expected format.
For instance, did you take into account the 'ar' field used in the perl pack statement? You might be off in the resulting packed data by one field because of that.
I haven't looked at this very long, but the first thing I noticed was that you have one open paren and three closing. Is "time" supposed to be $time?
The problem is that php preg_split is converting it to an array. You need an unsigned char, so use
Let know how it goes.
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():
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:
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.
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 codeC
wants 4 characters, that is the cause of the error.The code should be something like
Then, there is no reason to use
preg_split()
in this case, whenexplode()
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.