Bay Cao và Bay Xa – Fly High and Fly Far

July 24, 2009

How to install WWW::Contact module for import contact from yahoo, gmail, AOL from perl cgi website

Filed under: Perl, Programming — doqkhanh @ 1:29 PM

In this small tutorial, I will show you how to install WWW::Contact module to implement import contact feature from yahoo, gmail, AOL in your perl-cgi website.

I am using centos 5.3 and its bash shell in Poderosa, with a root account:
#find /usr/lib/perl5/5.8.8/CPAN/Config.pm path
locate CPAN/Config.pm

#open to edit and make sure we have access to the Internet
vim /usr/lib/perl5/5.8.8/CPAN/Config.pm
#’connect_to_internet_ok’ => q[1],
#’urllist’ => [],

#Download WWW::Contact packet
wget http://search.cpan.org/CPAN/authors/id/F/FA/FAYLAND/WWW-Contact-0.27.tar.gz

#un compress
tar -xvzf WWW-Contact-0.27.tar.gz

#check config
cd WWW-Contact-0.27
perl Build.PL

#you could see something like this
Checking whether your kit is complete…
Looks good

Checking prerequisites…
Looks good

Deleting Build
Removed previous script ‘Build’

Creating new ‘Build’ script for ‘WWW-Contact’ version ‘0.27′

#If there is any missed module, install it.
Checking prerequisites…
– ERROR: Net::Google::AuthSub is not installed
– ERROR: HTML::TokeParser::Simple is not installed
– ERROR: WWW::Mechanize is not installed
– ERROR: Crypt::SSLeay is not installed
– ERROR: JSON::XS is not installed
– ERROR: Text::vCard::Addressbook is not installed
– ERROR: WWW::Mechanize::GZip is not installed
– ERROR: Moose is not installed

#To install missed modules
perl -MCPAN -e shell
install Net::Google::AuthSub
install HTML::TokeParser::Simple
install WWW::Mechanize
install Crypt::SSLeay
install JSON::XS
install Text::vCard::Addressbook
install WWW::Mechanize::GZip
install Moose

# you may need force install for SSLeay module
force install Crypt::SSLeay

# try to install our Contact module
perl -MCPAN -e shell
install WWW::Contact

#if still cannot install Contact module in automatic mode, try to install it manually
perl Build.PL
./Build
./Build test
./Build install

Congrats ! Your sample should work well now.

May 25, 2009

perl -MCPAN -e shell TIPs, TRICKs

Filed under: Other, Perl, Programming — doqkhanh @ 10:06 AM

1. With history
Using   perl -MCPAN -e shell -xdg
Instead of perl -MCPAN -e shell

You can using up/down arrow key to get local history.

2. When you get this message
CPAN.pm panic
Simply delete your lock file and reload cpan to continue without any error. Thanks Mr Bang for this handy tip.

3. You can set ftp site to empty for better support in case your wget cannot get file with cpan shell
Try to locate Config.pm in cpan directory
# locate CPAN/Config.pm
And edit it with vim, vi or any editor like that and make sure your urllist is empty, it is empty but it will working like a champ.
'urllist' => [],

4. Update cpan
# Backup your current module list
perl -MCPAN -e autobundle
# That will create a file with a name like
## /root/.cpan/Bundle/Snapshot_yyyy_mm_dd_00.pm
# Enter CPAN
perl -MCPAN -e shell -xdg
# Update
install Bundle::CPAN
# Reload cpan
reload cpan

April 20, 2009

Perl does not do any automatic dereferencing for you

Filed under: Other, Perl, Programming — Tags: , — doqkhanh @ 12:49 PM

No Automatic Dereferencing

Perl does not do any automatic dereferencing for you. You must explicitly dereference using the constructs just described. This is similar to C, in which you have to say *p to indicate the object pointed to by p. Consider

$rarray = \@array;

push ($rarray,  1, 2, 3);   # Error: $rarray is a scalar, not an array

push (@$rarray, 1, 2, 3);   # OK

push expects an array as the first argument, not a reference to an array (which is a scalar). Similarly, when printing an array, Perl does not automatically deference any references. Consider

print "$rarray, $rhash";

This prints

ARRAY(0xc70858), HASH(0xb75ce8)

This issue may seem benign but has ugly consequences in two cases. The first is when a reference is used in an arithmetic or conditional expression by mistake; for example, if you said $a += $r when you really meant to say $a += $$r, you’ll get only a hard-to-track bug. The second common mistake is assigning an array to a scalar ($a = @array) instead of the array reference ($a = \@array). Perl does not warn you in either case, and Murphy’s law being what it is, you will discover this problem only when you are giving a demo to a customer.

Copyright: http://oreilly.com/catalog/advperl/excerpt/ch01.html

March 27, 2009

Perl: @INC array

Filed under: Perl, Programming — Tags: — doqkhanh @ 1:23 PM

The @INC array is a list of directories Perl searches when attempting to load modules. To display the current contents of the @INC array:

# perl -e “print join(\”\n\”, @INC);”


The following two methods may be used to append to Perl’s @INC array:

1. Add the directory to the PERL5LIB environment variable.
Centos/Redhat:
# export PERL5LIB=/usr/local/src/api/soap

2. Add use lib directory; in your Perl script.
#
## using perl module with direct link to module directory with use lib
# use lib qw (/usr/local/src/api/soap);
#

For more information, read the perlrun manpage or type perldoc lib

February 25, 2009

Several ways to execute a shell script in Perl

Filed under: Perl — Tags: — doqkhanh @ 3:23 AM

There are several ways to execute a shell script in Perl :

#!/usr/bin/perl -w

use Shell qw(cat ps cp df ssh su);
print "Content-type: text/html; charset=Shift_JIS\n\n";

su ("neededuser");
@result = qx{ sudo su username -c '/home/perl/cgi-bin/CheckMailStatus.sh' };

$cmd = "sudo su neededuser -c '/home/perl/cgi-bin/CheckStatus.sh' ";
$data = qx/$cmd/;

$result = system ("sudo su username -c 'echo hello '");
print $data;

exit;

August 21, 2008

Get ranking with only 1 MySQL Query

Filed under: MySQL, Perl, Programming — Tags: , — doqkhanh @ 7:21 AM

Sometime, you need to order and get member ranking base on one or more condition, you can get all information and use a array to get need ranking, but today I will introduce to you a better way, and certainly – faster way to get it: using just 1 query to get member ranking.

This is query in query command:

SET @rownum := 0; #Create counter variable
SELECT *
FROM
(
SELECT DISTINCT(FieldID), @rownum := @rownum + 1 as ranking
FROM TableName.FieldName
WHERE
FieldID = '27'
) AS NewTable
WHERE NewTable.FieldID = '00022'

This is perl code for the above query:

my $sql0 =" SET \@rownum := 0;";
my $sql1=" SELECT ranking FROM ..... LIMIT 1;";

$db->do($sql0);
$sth=$db->prepare($sql1);

$row=$sth->execute;

if(defined($row) && $row == 1)
{
$rec = $sth->fetchrow_arrayref;
$result = $rec->[0];
}
$sth->finish;

Comparison Operators – How to compare values in Perl

Filed under: Perl, Programming — Tags: — doqkhanh @ 2:26 AM

Perl actually has two sets of comparison operators – one for comparing numeric values and one for comparing string (ascii) values.

== eq equal
> gt greater than
>= ge greater than or equal to
< lt less than
<= le less than or equal to
!= ne not equal

August 7, 2008

Converting to sjis to utf-8

Filed under: Perl, Programming — Tags: , — doqkhanh @ 6:38 AM

This code can convert a Japanese Shift JIS string to a utf-8 string. Thank 中島さん (Mr Nakajima) for this useful code snippet.

use Unicode::Japanese;

my $keyword="";
$keyword = "something in Japanese like これわ日本語です。";

# use utf-8
my $converter = Unicode::Japanese->new($keyword, 'sjis');
$keyword = $converter->get;

#Su dung $keyword bt

August 1, 2008

Javascript UrlEncode work well with PHP and Perl

Filed under: Perl, Programming — Tags: — doqkhanh @ 9:47 AM
    Javascript UrlEncode work well with PHP
    /**
    * \summary: http://kevin.vanzonneveld.net
    * \author:   Original by: Philip Peterson
    *              improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net), doqkhanh (http://quockhanh.info)
    * \example: urlencode('Kevin van Zonneveld!');
    * \returns: 'Kevin+van+Zonneveld%21'
    */
    function urlencode( str ) {
    var errorMessage = "Javascript error at urlencode() function in kingpot.js. Please contact GNT's site administrator.";
    var ret = str;
    try
    {
        ret = ret.toString();
        ret = encodeURIComponent(ret);
        ret = ret.replace(/%20/g, '+');
    }
    catch(err)
    {
        alert(errorMessage);
    }

    return ret;
    }

    PERL UrlEncode and UrlDecode
    sub urlencode
    {
        my $str = shift;
        $str =~ s/([^A-Za-z0-9])/sprintf("%%%02X", ord($1))/seg;    return $str;
    }    

    sub urldecode
    {
        my $str = shift;
        $str =~ s/%([A-Fa-f0-9]{2})/pack('C', hex($1))/seg;
        return $str;
    }

    Faster solution:
    $NeedEncodeingString =~ s/([^A-Za-z0-9])/sprintf("%%%02X", ord($1))/seg;
    $NeedDecodingString =~ s/\%([A-Fa-f0-9]{2})/pack('C', hex($1))/seg;

Invoke Amazon Web Services with Perl

Filed under: Perl, Programming — Tags: , — doqkhanh @ 9:16 AM

use LWP; # This library provides API to call Amazon Webservice

# These xml library provides API to paser XML from Amazon Webservice
use XML::Parser;
use XML::Simple;
use Data::Dumper;

# Create a user agent object
my $ua = LWP::UserAgent->new;
$ua->agent(“ApplicationName(c)YourCompany/Version 1.0 “);

#Create a request
my $SubscriptionId = “0MB1VZ********NYEQR2″;
my $request =  “http://webservices.amazon.co.jp/onca/xml?Service=AWSECommerceService&SubscriptionId=$SubscriptionId&Operation=ItemSearch&SearchIndex=Music&Keywords=$keyword&ResponseGroup=Medium,Tracks&Binding=CD&ReleaseDate=Latest”;

my $req = HTTP::Request->new(POST => $request);
$req->content_type(‘application/x-www-form-urlencoded’);
$req->content(‘query=libwww-perl&mode=dist’);

# Pass request to the user agent and get a response back
my $res = $ua->request($req);
my $ItemCollection;

my $dump_result; #This avariable using to unsderstance returned data structure

# Check the outcome of the response
if ($res->is_success)
{
#Get XML Page
$tmp = $res->content;

#Try paser by simple xml library
$ItemCollection = XMLin($tmp);

# Get data array structure
$dump_result = Dumper($ItemCollection);

#Try parse and get needed data
if($ItemCollection->{Items}->{TotalResults} ne 0)
{
if($ItemCollection->{Items}->{TotalResults} ne 1)    #if an array
{
$url = $ItemCollection->{Items}->{Item}->[0]->{ImageSets}->{ImageSet}->{MediumImage}->{URL};
}
else #if not an array
{
$url = $ItemCollection->{Items}->{Item}->{ImageSets}->{ImageSet}->{MediumImage}->{URL};
}

}

}

Test new Search Engine Result

Filed under: Perl, Programming — Tags: — doqkhanh @ 2:28 AM

Search result for “doqkhanh” keyword.
No 1: cuil.com 174
No 2:google.com 113
No 3:search.yahoo.com 65
No 4:live.com 57

Whew…

Wow. That was intense. Looking back at the first 48 hours since launch, it was quite an experience. After a lot of hard work, we were thrilled to begin offering our new approach to search. We were even more thrilled with the interest, and traffic, we received.

In fact, it was overwhelming—literally. While we had planned for a large number of searches on our first day, we hadn’t planned on more than 50 million. After all, that’s in the same ballpark as Microsoft’s Live Search and approaching Yahoo!. And they have a bit more infrastructure than our small start-up.

So for a good part of the first day, the traffic volume simply outstripped our ability to respond. Some machines failed. Some bugs were found. Some of our redundancies…weren’t so redundant. This meant some searches didn’t get the best results. Some didn’t get any.

And yet, for a lot of searches, Cuil did provide users with new results, different from the ones folks have gotten in the past, according to the reports we’ve received. This is one of our goals—to give people an alternative to existing approaches.

Thank you very much for the feedback. The emails we’ve gotten at feedback@cuil.com have been very helpful, telling us areas you enjoy—such as the layout and the search by category feature—and areas where we need to improve—image matching, for example. We read them, so please keep them coming.

At Cuil, we are tackling some of the big challenges in search, from finding ways to search more of the Web, to finding results by analyzing the content on a page, to providing images with our results to help you pick the page you want. These are difficult problems, and we know we have more work to do.

We are incredibly proud of what this small team of 30 employees has been able to build from scratch already, and we are committed to improving Cuil every day. Thank you for trying us out.

Tom, Anna and Russell

Blog at WordPress.com.