1

Is there a php library I can use to convert an associative array in perl to an associative array in php ? If not, is there any recommended way of doing this ? Regular expressions ? A bunch of explode and implode calls ?

I want to go from

my %arrayname = (
    key1 => "Value1",
    key2 => "Value2",
    key3 => "Value3",
...

to

$arrayname = array(
        "key1" => "Value1",
        "key2" => "Value2",
        "key3" => "Value3",
1
  • I think you mean $arrayname = array(…). Also, you're basically trying to parse Perl source code into PHP? Commented Nov 11, 2010 at 12:29

1 Answer 1

4

If you have Perl on your server, you use:

print 'Array(';
while (($key, $val) = each(%arrayname)) {
    print "'$key' => '$val',";
}
print ');';

You can also have a look at the PECL Perl package, this library integrates a Perl parser in PHP.

You can use an online Perl interpreter with example code and working (there is just one extra comma at the end).

I created a regex that almost works. You can try it, but it depends on the structure of the Perl array:

preg_match_all(#\%(.+)\s=|\n(.+).*#);

Example data:

my %arrayname = (
    key1 => "Value1",
    key2 => "Value2",
    key3 => "Value3"
)

You can test it with the Regular Expression Test Tool.

Sign up to request clarification or add additional context in comments.

10 Comments

+1 definitely agree it's easier to produce source in a foreign language than it is to parse a foreign language's source.
Perl is not an option in this case, I'm parsing someone else's perl config files from PHP.
@tchrist I never knew that php was also from M$, now it all makes sense :P
@sjobe: The point is that only Microsoft systems neglect to include Perl; all others have it, and even Prisoners of $Bill can get it easily enough. It is completely unreasonable to expect to parse Perl using anything but perl, and that remains true no matter what. It is also provably impossible. So do the easy thing, not the impossible one.
@sjobe It is not true, from a theoretical point of view, that there are only so many ways to represent the contents of an associative array in Perl. There are infinitely many ways, although I leave it to you to figure out whether that’s ℵ₀, ℵ₁, or worse. In your discrete case, the possibilities may be more limited, but we have no way of knowing that because the problem space has not been sufficiently well defined or even described.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.