Showing posts with label perl. Show all posts
Showing posts with label perl. Show all posts

2011/10/27

selectall_arrayref vs. selectall_hashref

Both selectall_arrayref and selectall_hashref are method that combines "prepare", "execute" and "fetchall_arrayref" into a single call. The former returns a reference to an array containing a reference to an array (or hash, see below) for each row of data fetched. And the latter returns a reference to a hash containing one entry, at most, for each row, as returned by fetchall_hashref(). Note that selectall_hashref return the ordered list of result as statement intented to, for example,
$sql = \"select ename from employee order by ename\"; 
$hash_ref = $dbh->selectall_hashref($statement, \"ename\");
The %$hash_ref does not contant the ordered list of ename, because it's hash. So the get the ordered list, you need to sort the hash. like
sort(%$hash_ref);
In some case, the statement has "order by" multiple fields, it's not easy to sort hash to having the same order as statement trying to, so you may just use selectall_arrayref, which can also return a reference to a hash, for example,
$sql = \"select ename, eage from employee order by ename, eage\";
my $emps = $dbh->selectall_arrayref(
      $sql,
      { Slice => {} }
  );
  foreach my $emp ( @$emps ) {
      print \"Employee: $emp->{ename}\n\";
  }
For more perl dbi usage, click here http://search.cpan.org/~timb/DBI/DBI.pm

2011/07/27

Headache of ISO-8859-1 to UTF8

In Perl, you can use encode ('UTF-8', $iso-text-str) to convert ISO-8859-1 encoded string to UTF-8 encoded string. And in PHP, you can use utf8_encode($iso-text-str) to do the converting.
However, you may be out of luck, for after being converted, some characters could be funky and not what you wanted to see. I think this is because, some characters in UTF8 are invisible, like x80 - x9f (see the following ISO-8859-1 characters list images)





Because I  only care of those regular characters, like \x20-\x7F or \xA9 or \xAE or \x99,  I strip other characters before applying encoding function.
In Perl
$content =~ s/[^(\x20-\x7F|\xA9|\xAE|\x99)]+//g;
$content = encode('utf8', $content);

In PHP
$content = preg_replace('/[^(\x20-\x7F|\xA9|\xAE|\x99|\n)]+/', "", $content);
$content = utf8_encode($content);

UPDATE: Actually, I found that in Perl, encode function cannot correctly convert \x99 to ™. Finally my solution is the following,
open (FILE,  ">$your_file") || die "couldn't write to epcmf file\n";
   binmode(FILE, ":UTF-8");

   $title =~ s/[^(\x20-\x7F|\xA9|\xAE|\x99)]+//g;
   $title =~ s/\x99/™/g;
   $title =~ s/\xAE/®/g;
   $title =~ s/\xA9/©/g;
   print FILE $title;

Note:

  1. You should edit your script in UTF-8, for example, in PUTTY, you can change your character set to UTF-8 at Configuration > Windows > Translation
  2. UTF-8 is different to utf8, so in make sure you write it as binmode(FILE, ":UTF-8");

2009/08/25

Trim in perl

Perl does not come with trim function, but you can crate one easily:

# Perl trim function to remove whitespace from the start and end of the string
sub trim($)
{
    my $string = shift;
    $string =~ s/^\s+//;
    $string =~ s/\s+$//;
    return $string;
}
# Left trim function to remove leading whitespace
sub ltrim($)
{
    my $string = shift;
    $string =~ s/^\s+//;
    return $string;
}
# Right trim function to remove trailing whitespace
sub rtrim($)
{
    my $string = shift;
    $string =~ s/\s+$//;
    return $string;
}

2009/06/18

Remove all posts

Sometimes you may want to remove all posts from your Wordpress. You can do this from Wordpress dashboard, but you have to do delete them page by page, and each page has only 20 posts.

If you really wanted to remove all post at a time, here is Perl script to do so.

use WordPress::XMLRPC;
my $o = WordPress::XMLRPC->new({
username => 'admin',
password => 'yourpass',
proxy => '/path/to/your/xmlrpc.php',
});
#print $o->getPost();
my $post = $o->getRecentPosts(500); #500 meant get 500 posts
for $p (@$post) {
 $id =  $p->{'postid'};
 #print "$id\t";
 $o->deletePost($id);
}
PERL WORDPRESS XMLRPC Module can be found at here

2007/03/08

my $line_old = $_; my $line = $line_old; my @lines = split (/,/ , $line); foreach my $item (@lines) { do something } $line = join ("," , @lines); ####split does not take the trailing empty element if ($old_line =~ /.*(,+)$/) { $line .= $1; }

2006/12/10

CGI-BIN

WOW!
You have to set cgi-bin's permission as 755, otherwise, you will get error like 'Premature end of script headers', even you have higher permission for cgi-bin, for example, '775'.
It is a kind of weird, Hum!

2006/11/16

exit, return, die

exit: terminate the program, it will return 0
exit(1): terminate the program, return 256;
exit(2): terminate the program, return 512;

die: terminate the program, return 65280;

return: return from a function, and it cannot be used outside function.

Note: If the program use multithreading and one thread died, then the whole program will not end until all other threads end.

2006/11/15

Spawning other program in perl

1. Backtick:
`system call or other program `;
No standard output of system call/other program can be shown on the current standard output, but standard error will be shown.
You can use a variable to hold the standard output, and then print it out. For example:
$stand_out = `system call or other program`, print “$stand_out”;

2. System ( )
system (“system call/other program”)
Both standard output and standard error of system call/other program will be shown on the current standard output.
If you use:
$result = system (“system call/other program”)
You will get $result = 0, when there is no error in system call/other program, otherwise, you will get strange number like 256/-1.

2006/11/14

Delete multiple files in Perl

Just found a way to delete useless files in a current directory.


foreach $file (<*.tmp>) { # step through a list of .tmp files
unlink($file) || warn "having trouble deleting $file: $!";
}


reference

Soap

SOAP (Simple Object Access Protocol) is a way to make function calls upon classes and objects, which exist on a remote server.

2006/11/10

Using return + Multithread

There is a 'join' function in Perl when using threads module.


use threads;
use threads::shared;

my @t;
for my $i (1..$num)
{
push @t, threads->new(\&ajxss_wt, $i, $name[$i]);
}
for (@t) { $_->join;}

print "something";


Without 'join' here, "something" will be print immediately, but with 'join', print function will hold until every thread ends.

How to know if thread ends? It will check the return value from 'ajxss_wt' function.
So return 1 must have at the end of 'ajxss_wt' function.

As I found, it is better to make ajxss_wt simple.

Note: For a large number of threads, this code does not work well in cgi-bin. But we can embed this piece of code into system call.

Update: Just found firefox may not be able to support multithread in my case, but IE works fine.

2006/10/19

Tricky substitute


$original = "lib p($library)";
$original =~ s/$library/mylibrary/;
print "$original\n";

$original did not change at all, because $library is variable and it is undef in our case, so you cannot find the undef string in $orinial to change it to new string. What we can do is

$original =~ s/\$library/mylibrary/;

2006/10/09

Premature end of script headers

Sigh! Just because I set permission of cgi-bin to 775 instead of 755.

2006/09/19

Hash table is unordered

Create a table by:

for (my $i=0; $i<$#dat_array+1; $i++)
{
   $table{"$dat_array[$i]"} = "$res_array[$i]";
}

Print table by:

while ((my $key, my $val) = each (%table))
{
   print "$key\t$val\n";
}

You will get different order as you created in array.

2006/09/06

CGI.pm

Verify whether CGI.pm is installed and which version:

perl -MCGI -e print "CGI.pm version $CGI::VERSION\n";

2006/08/31

Run Perl script in a CGI script

The backtick opeartor can place a well-done Perl script in a CGI script. But a CGI script running on the web usually use a standard library:

/usr/lib/perl5/5.8.0

problem:
If that well-done Perl script use non-standard library in a specifical Path, you may get below error:

Can't locate XML/Xerces.pm in @INC ...


Solution:
Add a path to that non-standard library in the CGI script.

use lib '/usr/local/hive/lib/.....'

'export LD_LIBRARY_PATH=/usr/local/....:${LD_LIBRARY_PATH}'

2006/08/24

@INC

@INC is a special Perl variable which is the equivalent of the shell's PATH variable. Whereas PATH contains a list of directories to search for executables, @INC contains a list of directories from which Perl modules and libraries can be loaded.

When you use(), require() or do() a filename or a module, Perl gets a list of directories from the @INC variable and searches them for the file it was requested to load. If the file that you want to load is not located in one of the listed directories, you have to tell Perl where to find the file. You can either provide a path relative to one of the directories in @INC, or you can provide the full path to the file.

Source: http://perl.apache.org/docs/general/perl_reference/perl_reference.html#Description

Note: use
perl -e 'print join "\n", @INC'

to check what pathes have been defined, but it does not show the all pathes which being used.

2006/08/17

@ARGV

@ARGV is predefined variable to hold the command line arguments.
$#ARGV is the totoal number of arguments minus 1.
$ARGV[0] is the first argument.

For example:

perl test.pl one two three


@ARGV --> ("one", "two", "three")
$#ARGV --> 2
$ARGV[0] --> one

2006/08/16

A long string

To define a variable in Perl is pretty simple. A variable preceded with $ can present number, string, etc. When we want to present a long string, in order to avoid being misinterpreted we need put '\' to skip some charactor such as '%','%' ect.

One simple way is using a subroutine like below, but it cannot handle '@'.


sub GetLongString {
return << "LONG";
WHATEVER $%!~(*&^)(
LONG
}