Convert a Perl code to PHP

2020-05-09 17:15发布

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.

标签: php perl pack
8条回答
来,给爷笑一个
2楼-- · 2020-05-09 18:11

I think that the problem is that preg_split returns an array. So the array is inserted as the first char, the time as the second, and two chars are left.

I don't know how to fix this problem, but to create a temporary array:

$ip = explode('.','10.2.1.1');

And then:

echo pack("SSA12AC4L",
 '25',
 '00001',
 '2u7wx6fd94fd',
 'f',
 $ip[0],
 $ip[1],
 $ip[2]
 $ip[3],
 time()+(60*60));
查看更多
对你真心纯属浪费
3楼-- · 2020-05-09 18:12

It looks like you're having trouble with the fact that in Perl, if a function call is placed in the middle of a parameter list, and the called function returns a list, the items in that list are "flattened" to produce multiple arguments to the outer function; PHP doesn't do anything similar, and that's where you're getting your argument mismatch (the split should be producing four arguments to pack, but PHP only sees one -- an array value).

Fortunately the way around this is pretty easy, because there are builtin functions that will replicate what you need without any gymnastics. Try:

echo pack("SSA12ANL",
'25',
'00001',
'2u7wx6fd94fd',
'f',
ip2long('10.2.1.1'),
'1278761963');

or if that somehow fails:

echo pack("SSA12Aa4L",
'25',
'00001',
'2u7wx6fd94fd',
'f',
inet_pton('10.2.1.1'),
'1278761963');
查看更多
登录 后发表回答