From PHP to Perl


PHP array_unique in Perl

Posted in Other by gosukiwi on March 6, 2008
Tags: , ,

Well this function is very handy when you are working with flatfiles, or for example you dont have a category table on your mysql database, so entries have repeatead categories.

What the function array_unique does, is return an array without the repeated elements given in the array you gave as argument.

For example:

<?php
$array = array(1,2,1,3,4,1,2,6,4,5,1);
$array = array_unique($array);
sort($array);
print_r($array);
?>

That will print

Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5 [5] => 6 )

It deletted repeated elements, now, how to do that in perl?
Well that function does not exists in perl, anyways, you can create it, its not very hard… Here are some examples, this is the one i made

sub array_unique
{
my @list = @_;
my %finalList;
foreach(@list)
{
$finalList{$_} = 1; # delete double values
}
return (keys(%finalList));
}

It works exactly the same as PHP’s array_unique, someone at Cafe PM also suggested this one, which is shorter but to be honest i dont understand it much

sub array_unique
{
my %seen = ();
@_ = grep { ! $seen{ $_ }++ } @_;
}

That function also works the same as the one before, and the code in perl would be

#!/usr/bin/perl

use CGI’:all’;
use strict;

# Code…
sub array_unique
{
my %seen = ();
@_ = grep { ! $seen{ $_ }++ } @_;
}
# More code….

my @array = (1,2,1,3,4,1,2,6,4,5,1);
@array = sort(array_unique(@array));
print header, “@array”;

And that will print

1 2 3 4 5 6

Well, thats it, enjoy!

Advertisements

Redirect

Posted in Other by gosukiwi on December 6, 2006

Well, i think you all know how to redirect in PHP (header(‘Location: page.php’)) but, in perl, you have to set the header before the input, and what if you always include a header file, print the content, and then a footer file, or use some kind of “PHP” Navigation, including files?
Well, there is one way to do this, “Javascript”
You can redirect with Javascript from Perl!

First, you need to make a basic JS Code

function redirect(time, url)
{
$seconds = time*1000;
$url = url;
setTimeout(“window.location=$url”,$seconds);
}

That will redirect in x seconds, to an x url
And, for some Perl integration, i made this simple function

sub redirect
{
print ‘<script language=”javascript” type=”text/javascript”>redirect(‘.$_[0].’,\”.$_[1].’\’)</script>’;
}

And thats all! Now, when you want to redirect, just make

redirect(1,’mypage.pl’);

Thats the equivalent of PHP’s

header(‘refresh: 1; url=mypage.php’);

Well, i hope you find this useful :] Bye!

Is In Array?

Posted in Programming by gosukiwi on December 3, 2006

I was searching if there was a function like in_array of PHP in Perl, but there is not such function, but, it is still very easy to check!
This was useful for me so i hope it is for you
In PHP:

<?php
$string = ‘fin_helm’;
$array = array(‘full_plate’,’manteau’,’boots’,’two_handed_sword’,’fin_helm’);
if(in_array($string, $array))
{
print “$string is in the array”;
}
?>

In Perl:

#!/usr/bin/perl
my $string = ‘fin_helm’;
my @array = qw/full_plate manteau boots two_handed_sword fin_helm/;
if(grep $_ eq $string, @array)
{
print “$string is in the array”;
}

So, those codes do exactly the same.
If you don’t know much perl you will be wondering what does the grep function, the grep function examines each of an element of an array (represented with $_) and then we make a comparison or something with it, in this case $_ eq $string, grep, returns the elements with where true, in this case we are not requesting the elements, we are requesting a sacalar value, so, in perl 0 is false, and every other number is true, that will return 1, so its true, and the element is in the array 🙂
I hope you all find this useful, bye

BBCode and Regex

Posted in Programming by gosukiwi on November 23, 2006

BBcode is very popular on forums, if you have never heard of it you may have seen it and don’t know it’s name

BBcode looks like [b][/b] for bold, [url=url]linktitle[/url] for links, etc
I will show you how to make that with Perl and PHP
You need a basic knowledge of regular expressions. I will explain some basic stuff here.

What are Regular Expressions?

Basically, Regular Expressions (also called regexp) are templates that matches a given string.
For example
PHP:

<?php
$string = ‘Hello! Im fedekiller’;
if(preg_match(‘@fedekiller@i’,$string))
{
echo ‘We found fedekiller in that string.’;
}
else
{
echo ‘We could not found fedekiller in that string.’;
}
?>

In Perl:

#!/usr/bin/perl
use CGI’:all’;
print header, start_html();
my $string = ‘Hello! im fedekiller’;
if($string =~ /fedekiller/i)
{
print ‘We found fedekiller in that string.’;
}
else
{
print ‘We could not found fedekiller in that string.’;
}
print end_html;

Those codes will look for fedekiller in the given string, in perl, we use // and put the pattern there, but that was because we did not specify we were matching, if you want to use other separators, you can use for example || or {} but you have to specify you are matching. We will use // here, we dont want to complicate it so much, we also use i after the / to indicate that its CaSe InSeNsItIvE, we also specify case insensitive in PHP after the @
As you have probably realised, to match something in perl we use $string =~/pattern/;
And in PHP we use preg_match(@pattern@,$string);

Quantifiers
Quantifiers are used for repetition
* Matches 0 or more times
+ Matches 1 or more times
? Matches 0 or 1 time
{2} Matches exactly 2 times
{2,} Matches 2 or more
{2,5} Matches 2, 3, 4 or 5 times

Example:
Regex:

fe+dekil{2}er

Will Match:

feeeeeedekiller

Grouping
You can also match by group, using “(” and “)”, that will also make a variable with the content between the “(” and “)”
Example:
Regex:

(fede)+

Will Match:

fedefedefede

We can now acess to the content of the first () with the variable $1, for example if we did something like
Regex:

\[b\](.+?)\[\/b\]

Will Match:

[b]Something[/b]

And the variable $1 will contain Something
Alternatives
You can also match one thing OR other thing, using the ‘|’ bar
Example:
Regex:

(fede|killer)+

Will Match:

killerkillerfedekillerfede

Modifiers:
The modifiers are:
i – Will make it CaSe InSeNsItIvE
g – Global match
m – Multiple lines match
s – Single line match
x – Allow comments and white space in the pattern
e – Evaluate placement
U – Ungreedy pattern
Escape Character
Sometimes we want to use something for example () or {} but we dont want to use that function, for example in BBCode we want to match [b][/b] but no use the []’s function, so, we escape them with the \ character

Anchors
If you want something to match only at the beggining or the end of an string, we can use anchors
^ – Start of a string
$ – End of a string
\b – Word boundary
\B – Not word boundary
\< – Start of a word
\> – End of a word

What is boundary?
Word boundary is if we want to match that string only in a complete word, its for making sure for example we wont find cat in category.

Character Classes
\c – Control Character
\s – White Space
\S – Not white space
\d – Digit (number)
\D – Not digit
\w – Word
\W – Not word
\x – Hexadecimal digit
\O – Octal digit

Special Characters
\n – New Line
\r – Carriage Return
\t – Tab
\v – Vertical tab
\f – Form feed
\xxx – Octal character xxx
\xhh – Hexadecimal character hh
Well, i think that’s enought regex, we can now start with our bbcode function.
So, we want to match all between the [b][/b] tags, and aso the [i], [u], [img] and [url] tags.
In PHP:

function bbcode($content)
{
$content = preg_replace(“@\[b\](.+?)\[\/b\]@i”, “<b>$1</b>”, $content);
$content = preg_replace(“@\[i\](.+?)\[\/i\]@i”, “<i>$1</i>”, $content);
$content = preg_replace(“@\[u\](.+?)\[\/u\]@i”, “<u>$1</u>”, $content);
$content = preg_replace(“@\[img\](.+?)\[\/img\]@i”, “<img src=\”$1\” alt=\”\” />”, $content);
$content = preg_replace(“@\[url\](.+?)\[\/url\]@i”, “<a href=\”$1\”>[Link]</a>”, $content);
$content = preg_replace(“@\[url=(.+?)\](.+?)\[\/url\]@i”, “<a href=\”$1\”>$2</a>”, $content);
$content = str_replace(“\n”, ‘<br />’, $content);
$content = preg_replace(“@\[code\](.+?)\[\/code\]@i”, “<span class=\”box\”>$1</span>”, $content);
return($content);
}

We use the i after the @ to choose case insensitive, we also use the grouping function to get everything between the tags and then a variable wich contains that and put it inside the corresponding HTML tags
We do exactly the same in Perl
In Perl:

sub bbcode
{
$_ = $_[0];
s/\n/<br \/>/gi;
s/\[b\](.+?)\[\/b\]/<b>$1<\/b>/gi;
s/\[i\](.+?)\[\/i\]/<i>$1<\/i>/gi;
s/\[u\](.+?)\[\/u\]/<u>$1<\/u>/gi;
s/\[url\](.+?)\[\/url\]/<a href=”$1″ tager=”_blank”>$1<\/a>/gi;
s/\[url=(.+?)\](.+?)\[\/url\]/<a href=”$1″ target=”_blank”>$2<\/a>/gi;
s/\[img\](.+?)\[\/img\]/<img src=”$1″ \/>/gi;
s/\[code\](.+?)\[\/code\]/<div class=”code”><pre>$1<\/pre><\/div>/gi;
s/\[quote\](.+?)\[\/quote\]/<div class=”quote”>$1<\/div>/gi;
return $_;
}

in PHP, preg_replace is like this preg_replace(regex,replace_with,string)
In Perl
string =~ /regex/replace_with/;
If we dont specify the variable in Perl it will automatically use $_, but we have to specify that we are replacing with the letter s
So it will look like
s/regex/replacement/;

Well, thats all, i hope you all find it useful 🙂

Cookies

Posted in Programming by gosukiwi on November 21, 2006

Hello!

Today i will explain the differences between PHP and Perl with Cookies.

PHP is way better than Perl for cookies (maybe mod_perl could do a better job but PHP is still better) anyways, its not a big deal to get or set a cookie in Perl.

In Perl cookies can have maximum 6 attributes, in PHP they can have 7, most of them are optional, but they ones we are going to explain here are 3 attributes, which are in both languages, name, value and expire, the most basic attributes ;3

Before we start, i want to write the possible attributes, just for you to know them

In PHP:

Name
Value
Expire
Path
Domain
Secure
Httponly

In Perl:

Name
Value
Expire
Domain
Path
Secure Flag

Okay, now we can start explaining the 3 basic attributes, value, name and expire

In PHP:

set_cookie(‘name’,’value’,’expire’);

In Perl:

use CGI::Cookie;
$cookie = Cookie(-name=>’name’, -vaue=>’value’, -expires=>’expire’);
print header(-cookie=>$cookie);

In Perl, cookies must be sent before the html header, else, they wont stick, and you will probably see something like Set-Cookie: mycookie, etc

Okay, lets set a simple cookie, with the name user, the value fedekiller and the expire date 1 month

In PHP:

set_cookie(‘user’,’fedekiller’,time()+60*60*24*30);

In Perl:

use CGI::Cookie;
$cookie = Cookie(-name=>’user’, -vaue=>’fedekiller’, -expires=>’+1M’);
print header(-cookie=>$cookie);

In PHP we use the time function and multiply till we add one month (60 seconds * 60 minutes * 24 hours * 30 days)
In Perl, we just set +1M to make it last 1 month, if we want to delete a cookie, we have to use a negative value in expires, for example, in PHP would me time()-60*60… and in Perl it would be -1M

Now, lets read a cookie, with PHP is very easy

In PHP:

$_COOKIE[‘user’];

That will read the cookie value (in this case, fedekiller)

In Perl:

my %cookies = fetch CGI::Cookie;
$cookies{‘user’}->value

We set all cookies to the cookies hash, and then we just request the value.

I made a little function to get cookies in Perl so its a little bit easier

sub get_cookie
{
my %cookies = fetch CGI::Cookie;
if($cookies{$_[0]} ne ”)
{
$c = escapeHTML($cookies{$_[0]}->value);
}
}

We check if the cookie is not empty, because, if it is it will display a fatal error when we try to get the value.

Okay, thats all for now 🙂 i hope you all find it useful.

Bye!

Next Page »