From PHP to Perl


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!

Uploading a file

Posted in Programming by gosukiwi on November 20, 2006

Hi all! I will now show you how to upload a file in PHP and Perl

First of all the HTML, is the same for both languages, you just have to change the action.

We will make an example upload script, assuming that we want to upload an avatar.

HTML:

<form action=”myscript.php” method=”post” enctype=”multipart/form-data”>
<table border=”0″>
<tr>
<td>Upload your avatar </td>
<td><input type=”file” name=”avatar” /></td>
</tr>
<tr>
<td> </td>
<td><input type=”submit” name=”Submit” value=”Upload” /></td>
</tr>
</table>
</form>

Remember to change the action field
In that HTML code, we make a form with a POST method, and a multipart/form-data encryption. Thats very important!, so do not change it.
Then we make a simple file input and a submit button.

Now, the code 🙂

In PHP:

<?php
if($_POST[‘Submit’]) // If the form is submitted
{
$avatar = $_FILES[‘avatar’][‘tmp_name’]; // Avatar temp name
$avatar_name = $_FILES[‘avatar’][‘name’]; // Avatar name
$ext = array(‘.gif’,’.jpg’,’.jpeg’,’.png’); // Array with allowed extensions
$my_avatar_name = ‘avatar.gif’; // This is the name that our avatar will have
$do = false; // Set the variable $do as false
foreach($ext as $e) // Loop trought the array
{
if(eregi($e, $avatar_name) // If it find the extension in the avatar name, it will stop looping
{
$do = true; // Set do to true
break; // Stop looping
}
}
if($do) // If $do is true
{
if(copy($avatar, ‘avatars/’.$my_avatar_name)) // Copy the avatar
{
echo ‘Avatar uploaded!’; // if it could copy, we show this message
}
else
{
echo ‘Error uploading avatar :(‘; // Else, if it did not copy, we will show this message
}
}
}
?>

In Perl:

#!/usr/bin/perl
use CGI’:all’; # We use all CGI methods
if(param(‘Submit’)) # If the form is submitted
{
my $avatar = upload(‘avatar’); # Avatar temp name
my $avatar_name = param(‘avatar’); # Avatar name
my @ext = qw/.gif .jpg .jpeg .png/; # Array with allowed extensions
my $my_avatar_name = ‘avatar.gif’; # This is the name that our avatar will have
my $do = 0; # Set the variable $do as false
foreach (@ext) # Loop trought the array
{
if($avatar_name =~ /\.$_$/i)) # If it find the extension in the avatar name, it will stop looping
{
$do = 1; # Set do to true
last; # Stop looping
}
}
if($do) # If $do is true
{
open(AVATAR, “>avatars/$my_avatar_name”); # We create a file to write
binmode AVATAR; # We set it to bin mode to make sure it work in UNIX systems
while(<$avatar>)
{
print AVATAR; # Print the content byte per byte
}
close AVATAR; # Close the file
print header,start_html(); # Printe the html header and start with the html, header and body tags
if(-e “avatars/$my_avatar_name”)
{
print ‘Avatar uploaded!’; # if it could copy, we show this message
}
else
{
print ‘Error uploading avatar :(‘; # Else, if it did not copy, we will show this message
}
print end_html; # Close the body and html tags
}
}

Well, the codes are self-explained, i hope you all find it useful ^-^

Bye!

Mysql Interface

Posted in Programming by gosukiwi on November 19, 2006

Well, i will now post the basic differences between PHP and Perl and Mysql

Mysql is a very used sql database, used to store massive ammount of data.

Mysql is supported by alot of free hosting services, like awardspace.com, freewebsitehosting.net, etc

PHP and Perl are also supported by almost all hosting services.

I will show you the basic Mysql Interface with those two languages

That would be connect to a database, select a dabatase, execute queries (insert, delete, update), and numrows.

Connect to a database:

In PHP:

 

mysql_connect(‘host’,’user’,’pass);
mysql_select_db(‘database’)

In Perl:

 

use Mysql;
$db = Mysql->connect(‘host’, ‘database’, ‘user, ‘pass’);

 

Not very hard right? The main difference is that Perl uses a OOP interface to connect, so you will have to access the methods trought $db

 

Executing a query

In PHP:

mysql_query(“SELECT * FROM mytable”);

In Perl:

$db->query(“SELECT * FROM mytable”);

Not much difference, in perl is a little bit shorter, but basically the same.

Select Query

In PHP:

$q = mysql_query(“SELECT title, content FROM news ORDER BY id DESC LIMIT 3”);

In Perl:

my $q = $db->query(“SELECT title, content FROM news ORDER BY id DESC LIMIT 3”);

Still, not much difference, we just assigned that query to a variable.

Display Content

In PHP:

$q = mysql_query(“SELECT title, content FROM news ORDER BY id DESC LIMIT 3”);
while($r = mysql_fetrch_array($q))
{
echo ‘Title: ‘.$r[‘title’].'<br />’.Content: ‘.$r[‘content’];
}

In Perl:

 

 

 

 

$q = $db->query(“SELECT title, content FROM news ORDER BY id DESC LIMIT 3”);
while(%r = $q->fetchhash)
{
print ‘Title: ‘.$r{‘title’}.'<br />Content: ‘.$r{‘content’};
}

Now, in PHP, we use an array with keys and values to hold the data, but in Perl, arrays are only numeric, and we have to use hashes to have a key and value interface. We could have used fetcharray instead of fetchhash but thebn, we would have to use $r[1] instead of $r{‘content’}. That does not happen with PHP, because PHP arrays can have only values with numeric keys, or act like Perl hashes or Python dictionaries.

 

 

 

 

Updating and deleting

In PHP:

$id = $_GET[‘id’];
$uq = mysql_query(“UPDATE news SET content=’$content’ WHERE id=’$id’ LIMIT 1”);
$dq = mysql_query(“DELETE FROM news WHERE id=’$id’ LIMIT 1”);
if($uq && $dq)
{
echo ‘Queries executed successfully’;
}
else
{
echo ‘There has been an error’;
}

In Perl:

use CGI’:all’;
my $id = param(‘id’);
my $uq = $db->query(“UPDATE news SET content=’$content’ WHERE id=’$id’ LIMIT 1”);
my $dq = $db->query(“DELETE FROM news WHERE id=’$id’ LIMIT 1”);
if($uq and $dq)
{
print ‘Queries executed successfully’;
}
else
{
print ‘There has been an error’;
}

Well, not many differences there, you can also use print in php, the ony differences between print and echo in PHP is that print prints only one line, and echo can print multiple lines.

Numbering Rows

In PHP

$q = mysql_query(“SELECT id FROM news”);
$r = mysql_num_rows($q);
print ‘Total Rows: ‘.$r;

 

 

In Perl

my $q = $db->query(“SELECT id FROM news”);
my $r = $q->numrows;
print ‘Total Rows: ‘.$r;

 

 

Not many differences too, in Perl, we refecence directly the query result to use the numrows method, in PHP we dont use a method, just a function, with the query as an argument.

We can also use PHP with an OOP mysql interface, but we have to make a class on our own.

Well, that’s all 😀 I hope it will be useful for you ^^