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

Saturday, March 31, 2012

class variables in Moose

Moose attribute didn't allow the reference rather than a CODE reference as a default value. That prevents the objects shared a attribute when initializing. Actually this is a good design. But How should I do when needing a shared attribute between objects? I may refer this as the concept of class variable.

The state variable in CODE reference may be competent with this role.

A Counter as an example here. We define a Counter class here.



A counter has a attribute "value" and a method "inc" to increment it.

Then We define a Person class.



The Person class has a attribute "name" and a shared attribute "count". The Counter is a state variable return from a anonymous CODE reference. That's the trick.

The BUILD hook increment the counter everytime a new Person is constructed.

Then we examinate the shared variable.



A global variable in package name may still work. But this way uses 'has' syntax sugar. :p

If you use builder to replace the default option. the subroutine used by the builder is just the class variable accessor from Class name, returning value as $person->count().

Saturday, March 3, 2012

Mysterious Timestamp

時間轉換大概是最惱人的「小」問題之一,每個語言的標準處理方式不盡相同。Perl 的 localtime() 是月份從 0 開始到 11 結束,Ruby 的 DateTime 是月份是從 1 開始的,不過 Perl 的 DateTime 月份也從 1 開始 (LOL)。背誦這些東西大概會發瘋。

不過 Epoch 沒有這個問題,任何語言上的 Epoch 應該都是一致的,有的只是時差問題,使用 Epoch 來初始時間物件大概是避開這問題的好方法之一,特別在不同語言間交換時間資料時,用 Epoch 交換後怎麼 format 都不會出問題。所以有些時間模組大概會像 Perl 的 DateTime 一樣實作 from_epoch() 這種 constructor。

就這點設計而言,Badger::Timestamp 大概是最好用的時間模組,其 constructor 支援 DateTime 模組的方式初始化外,還可以餵食 Epoch 和 ISO 格式的時間字串。一個簡單的 Epoch/ISO converter 只要八行。

什麼,你問說這八行程式有什麼用,有些跑了好幾年的 unix 系統上有著 crontab 執行著需要 timestamp 來分辨執行區段的分析器,有些要當天的零分零秒,有些要隔天的零分零秒。壞掉時有人會要你一定要「人工」處理,這八行就就是這樣來的。

附帶一提, Javascript 的 Date.UTC 和 Perl 的 localtime() 一樣,都是月份從 0 開始。


和 Badger::Timestamp 很像的 moment.js這時候就很好用了,其 constructor 用陣列初始化時雖然還是沒有改用 1 作為月份起始著實也讓我驚訝了一下。好險,這 constructor 支援用 Epoch 初始化(不過承襲 javascript 的慣例,是 millisecond),還可以用 Date.parse() 支援的字串初始化。這兩招可以避開月份的問題。

Tuesday, November 30, 2010

Tasting Perl6

At the moment that the first release of Rakudo Star has been announced over four months, binary packages or tested build in package managers have been provided in varieties of OS. If we want to taste Perl6 on Mac OS X, the best choice seems to be using Homebrew. Just type in $ brew install rakudo-star and run $ perl6. Rakudo Star in Homebrew has been updated to the newest version: 2010.10.

On Debian-like system, the best one should be using PPA of dexter on LaunchPad. The version falls behind Homebrew a little to be 2010.09. Because the Rakudo Star requires Parrot 2.8+, we also have to add PPA of Parrot to satisfy. Command $ sudo apt-add-repository ppa:dexter/rakudo-pkg ppa:dexter/parrot-pkg and run update, install. Then have fun!

Tuesday, November 23, 2010

Intro to App::CLI

My first meet with App::CLI is in the summer of 2008, trying to write JiftyX::Fixtures. Without abundant PODs coming with this module, it took me almost one day to understand this module through trial and error. Since, I write this intro to reveal more power from this module; even I have contribute some code and DOCs to the project.

Actually, App::CLI is a really powerful module having central idea similar to the dispatcher in many web application frameworks such as Rails. When we are trying to create yet another handy CLI tool for our daily working, here is a recommended architecture to use App::CLI:

MyApp
-> The kernel of our new tool

MyApp::*
-> All other module forming the mechanism
-> of our new tool, e.g. MyApp::Config
-> for loading configuration

MyApp::Command
-> The dispatcher serving the invoking commands

MyApp::Command::*
-> All subcommands invoked by MyApp::Command

MyApp::Command::*::*
-> All subsubcommands invoked by specific subcommand

MyApp::Command::*::*::*
-> subsubsubcommands *god*

After deciding what command we need to implement, we only have two things should be done. The first is making MyApp::Command be able to dispatch. What we need to do is only add use base qw(App::CLI); into it.

Now, in MyApp.pm or our script, where we want to invoke command, we can just say
MyApp::Command->dispatch();
MyApp::Command would automatically use @ARGV to determine what (sub)command it should invoke and find its package to *require*. For example, if we type $ myapp list user --sort age in terminal, the @ARGV would be qw(list user --sort age), and MyApp::Command would require MyApp::Command::List::User, create its instance as $cmd, assign $cmd->{sort} as 'age', finally invoke $cmd->run_command().

So, The second thing, most of we need to effort, is to implement our (sub)commands. it's a bit like writing Controllers of Rails. If the URL matches /foo/bar/:id, the Action #list() of Controller Foo::Bar would handle the request, and @id would be assign value. If users type $ myapp list nickname --name /mark/ MyApp::Command::List::Nickname would handle the command and $instance->{name} would be assign string /mark/. For this case, we can write as below.

package MyApp::Command::List;
use base qw(App::CLI::Command);
use constant subcommands => qw(User Nickname);
use constant options => (
"h|help" => "help",
);

sub run {
my ($self, @args) = @_;
if ($self->{help}){
# output PODs when $ myapp list --help
}
# do something when user type like
# $ myapp list arg1 arg2 --opt1 --opt2 opt_arg2
# and arg1 doesn't equal to User or Nickname
}



package MyApp::Command::List::Nickname;
use base qw(App::CLI::Command);
use constant options => (
"name=s" => "name",
);

sub run {
my ($self, @args) = @_;
$name = $self->{name} #=> /mark/
# query the data base via condition /mark/
}

It completes. Note the we can specify all possible subcommands in constant subcommands of and give all possible options in constant options to all (sub)commands and just implement &run() the (sub)command would be done. And finally, note we can cascading subcommands infinitely. That is the core power of this module starting from v0.2.

Enjoy.

Friday, November 13, 2009

Library for Numerical Computing

Briefly summarize some numerical library here. It looks there are too many useful tools. Either for parallel computing or for matrix, numerical calculating and plotting.

PLOT:

MatPlotLib: it seems to be the most awesome plotting tool among this list

PGPlot: C library, also have binding in Perl, Python,Ruby

PLPlot: cross-platform plot library, also have binding in Perl

Scientific Python

MRPlot


PARALLEL:

MPI Ruby: MPI Ruby binding

PyMPI: MPI integrated Python interpreter

MPI for Python Python MPI binding

Simple Remote Python : SrPy

Parallel Python


CALCULATION:

Perl Data Language: difficult to be categorized. Including calculating, plotting together. include FFTW, PGPlot, PLPlot, and many data processing tool such as HDF. Awesome Environment!

MPMath: Multi-Precision math functions collection.

RNUM

NArray

LibFFTW, also have binding in Perl, Ruby

Ruby DCL

LAPACK

SciPy

NumPy

GNU Scientific Library: C library, also have bindings in Ruby named Ruby/GSL and Ruby-GSL. and Python

RSRuby: bridge between Ruby and R

ARTICLES:

Ruby for Science

 

Sunday, August 30, 2009

Discussion about anonymous function in Perl and Ruby

Just for fun, tonight I write a methods invoking two anonymous functions to iterate a Range with specified condition in Ruby. It looks like
class Range
def each_satisfy()
end
end
And I want to invoke it as

(1..10).each_satisfy(condition_lambda, callback_lambda)

(1..10).each_satsify { |n| ...condition statment... } do |n|
...callback statement...
end
When I try to define its prototype as
def each_satisfy(&condition, &callback)
end
Ruby Interpreter broke with syntax error. So that, finally I write it as

def each_satisfy(condition, &callback)
self.each do |n|
yield n if condition.call n
end
end
and it should be used as

(1..10).each_satsify lambda { |n| ...condition statment... } do |n|
...callback statement...
end

It reminded me that Perl also has the same problem. Even when we declare

sub each_satisfy(&&) {

}

Still only first sub keyword could be omitted. That means we should invoke it as

each_satisfy { ... condition ... } sub {
my ($iter) = @_;
... callback ...
}

The only difference is Perl omitted the first (sub) and Ruby omitted the last (lambda).

I do want to figure out WHY they could not be designed to accept arbitrary quantity of anonymous functions.

 

Sunday, August 23, 2009

LWP, cURL, OpenSSL and Posterous

The fun of programming is there is always subtle mechanism in implementation. It costs time to discover but sometime is deserving. for example.

$ curl --basic -u <user> http://example.com/api/

$ echo -n "user:pass" | openssl base64 -e

and



to



 

Saturday, August 15, 2009

Can't locate Git.pm in @INC

Well, the installation of Github::Import worked well on Linux boxs but always reported "can't locate Git.pm in @INC" on Macintosh boxs. It is just a little trick and the answer is here.

Git.pm comes with git instead of being a part of CPAN. Building a copy of git-core or copying from other box solve it quickly.

 

Monday, July 6, 2009

Data::Model

Data::Model is a new ORM created by yappo, Its usage style is similar to DataMapper and Jifty::DBI.

Different from most famous equivalent, Data::Model handles multi-database. In order to do that, every model was appointed its database and table name in addition to its schema specification.

Let's see a simple example:



This is a simplest model in Data::Model, Only two DDL in it.

The first, base_driver( $driver ) specify which database the model would connect to. $driver is a Data::Model::Driver::DBI object. Write those diffusion code in every model is really not perlish, so we extract all possible drivers to MyApp::DB::driver().



The second, pass the table name and schema to install_model(), this step is the same as above two ORM system. and then, all thing done. By the way, columns() is the best syntax sugar provided by Data::Model::Schema.

Wait... Because Data::Model is too young to do auto_migration, we simply write MyApp::DB::make_schema() to do that. Finally, we could do simple CRUD in our application. as below.



Though Data::Model is too young to have some important feature such as validator and hook, even has no ability to handle relation between two table. The prototype is really exciting.

[Chinese Version]

 

.

Tuesday, April 7, 2009

Class::Implant - No &import() !

Class::implant is a experimental little helper implemented when I developed Railsish with gugod. Manipulating mixin and inheritance outside package is its primary function, also with abilities to select methods which would import.

Original idea is inspire by the purpose: we want to import whole Helper methods into Controller which the Helper is named after. And it is should not be left to framework users to do it by themself. In Ruby, we just need to write
XxxController.send(:include, XxxHelper)
In Perl, it can also be written as
eval qq{ package XxxController; use XxxHelper; }
But a tedious &import() should be write in XxxHelper as follow.
sub import {
for (qw(hello world foo bar method...)) {
*{blah::$_} = \&$_
}
}
and edit the export methods list by hand.

Even use Exporter and edit @EXPORT and export by symbol :all, users still need to do follow by hand
use base Exporter;
our @EXPORT = qw(..);
Class::Implant provide simplified equivalent.

package main;
use Class::Implant;
implant "XxxHelper", { into => "XxxController" };

Everything done! All methods in XxxHelper is imported into XxxController!

If call use Class::Implant in other package, default import target would become it. That means, above code is the same as follow:

package XxxController;
use Class::Implant;
implant "XxxHelper";

In the release 0.02_01, two other options work. { inherit => 1 } make imported packages appear in @ISA of import target. { match => pattern } filter, and import methods conform to pattern.

For example,

package main;
use Class::Implant;
implant qw(Foo Bar), { into => "Cat", match => qr{h\w+} };

means import methods whose name start with h in Foo and Bar into Cat.

I also write UNIVERSAL::Implant. As its name, require once, and write as follow everywhere.

Cat->implant qw(Foo Bar), { match => qr{h\w+} }

Do the same thing as previous example. That means, caller package Cat assign { into => "Cat" }.



Chinese Version is @ Chupei.pm.org

 

Saturday, March 14, 2009

REPL in Perl

Read-Evaluate-Print Loop 在現代語言中非常常見,諸如 Scheme, Haskell, Ruby, 與 Python 都有內建,實際工作時是非常實用的工具,Perl 6 也即將內建 REPL Shell,Perl 5 則沒有。

這幾天偶然想在 Perl 中使用 REPL,搜尋了一下,在 use.perl.org 得到 2007 年發表的這篇文章,介紹了四個以 Perl 5 實做的 REPL Shell,翻譯如下。

Continue reading REPL in Perl.

 

Saturday, January 3, 2009

GitHub Creator

Install
# cpan Git::Github::Creator

Setting in ~/.github_creator.ini
[github]
login_page="https://github.com/login"
account=joe@example.com
password=foobar
remote_name=origin
debug=1
Then, in local git repository
github_creator --name my-project --desc "an awesome thing"

Arguments are optional in a Perl module with META.yml.

GitHub Creator's repository and manual on cpan

 

Thursday, November 6, 2008

perl work with growl

Excerpt from
http://oreilly.com/catalog/9780596526740/toc.html
and
http://search.cpan.org/~cnandor/Mac-Growl-0.67/lib/Mac/Growl.pm

A quick method to post notification to Growl.


#!/usr/bin/env perl

use warnings;
use strict;

use Mac::Growl qw(:all);

Mac::Growl::RegisterNotifications(
# register your application in Growl before posting.
# just one time enough.
'growlalert', # app name
['alert'], # all notification
['alert'], # default notification
);

Mac::Growl::PostNotification(
# post notification to Growl
"growlalert", # app name
"alert", # notification type
"this is a title", # alert title
"this is a description", # alert content
);


 

Monday, May 12, 2008

self.pm

some convenient usage I prefer. :p
package PackageName;
use self;
use strict;

my @args;

sub new {
@args = args;
for (@args) {
blah~!
}
bless {}, self;
}

1;

self.pm++
 
 

Saturday, April 26, 2008

learning perl review ch2


scalar:
    1.233, 2E-3, 3e45
# exponential float
123_123_234
# integer with underscore
0377, 0xff, 0b1111
# octal => 0, hexadecimal => 0x, binary => 0b
"hello,"."world!"
# concatenate with .
"hello" x 3
# repeat 3 time with x
"20fred" * 3
# ignore string when transform
$str = $str . "blah"; === $str .= "blah";
$int = $int ** 3; === $int **= 3;
# binary assignment operator
${word}blah~
# insert variable with dereference brace
eq == | ne != | < lt | > gt | <= le | >= ge
# string comparison operator

# return with \n at line end
defined($var)
# return true or false

initial parameters (perl -M)
    use warnings;
use diagnostics;

 
 

Friday, April 25, 2008

boring comparison

show complex data structure in perl and ruby

perl
#!/usr/bin/env perl
use warnings;
use Data::Dumper;

$a = ["a", "b", "c", { "key" => "value" } ];
print Dumper $a;


ruby
#!/usr/bin/env ruby
a = ["a", "b", "c", { "key" => "value" } ]
puts a.inspect
 
 

Sunday, February 24, 2008

CPAN mirror SOP

3 steps note for how to mirror CPAN for fast installation in organization:

First, using rsync mirror whole CPAN to local machine. Write rsync -avHP --delete rsync.nic.funet.fi::CPAN /var/www/CPAN >> /var/log/rsync.log 2>&1 into crontab for daily synchronization. This step supposes mirror site root is put at /var/www/CPAN.

Second, write apache VirtualHost as below.
<VirtualHost *>
ServerName cpan.yourdomain

DocumentRoot /var/www/CPAN
<Directory />
Options FollowSymLinks
AllowOverride None
</Directory>
<Directory /var/www/CPAN/>
Options Indexes FollowSymLinks MultiViews
AllowOverride None
Order allow,deny
allow from all
</Directory>

ErrorLog /var/log/apache2/cpan-error.log

LogLevel warn

CustomLog /var/log/apache2/cpan-access.log combined
ServerSignature On

</VirtualHost>

Restart your apache and access cpan.yourdomain. you can see it.

Third, register your mirror site at mirrors.cpan.org if you want to become a official mirror site.

 

Saturday, February 16, 2008

perl 和 ruby 的 twitter shell

twitter 最近紅透半邊天,perl 和 ruby 都有了 twitter api,現在還有 twitter shell,perl 的 twitter shell 利用 cpan 下 install Twitter::Shell 就可以得到 /usr/local/bin/twittershell, 使用方式為新增一個 yaml,如: touch ~/.twittershell.yml , 裡面填入
username: yourtwitteraccount
password: yourtwitterpassword
在 shell 下 twittershell -c ~/.twittershell.yml 就進入該 shell, help 可以得到幫助。

ruby 版本內建在 twitter 這個 gem 內, sudo gem install twitter 就可以得到 /usr/bin/twitter,直接在 shell 下 twitter 就可以得到幫助。不過 ruby 版本對 unicode 沒有支援,無法顯示中文,嘗試在 twitter gem 內的 twitter.rb 加入
require 'jcode'
$KCODE = 'u'
,不過沒有效果,作者也表示暫時不會加入 unicode 支援。

Sunday, December 23, 2007

jifty screencast

今天發現一個還不錯的 jifty 教學影片,位在
http://www.crium.univ-metz.fr/docs/devel/jifty/screencast.html

感覺上和 rails demo movie 差不多,晚點再來看看,不然 CPAN 上的 tutorial 實在不是我小小弱者看得懂的阿XD。

OS: CPAN 上的 tutorial 連基本的 MVC 架構都沒解釋清楚,實在也太把大家都當作強者了 Orz...

Thursday, December 6, 2007

CGI::UploadEasy

今天研究了一下 CGI::UploadEasy 模組,這是 CGI 上傳模組中最簡單的一個,只要在網頁內設定好上傳檔案用的 input 欄位,然後最後加上一行

my $upload = CGI::UploadEasy->new(-uploaddir=>"上傳資料夾",-maxsize=>"負數視為不設限,單位為KB",-tempdir=>"暫存資料夾");

這樣會自動判斷有多少個檔案要上傳,還有上傳檔案的 mime-type,最後可以用 $upload 物件內的方法來取得上傳檔案的參數。

不過這個模組不是很適合我目前希望的方式,他能夠指定的參數只有目錄,中文也有問題,另外兩個 CGI::Upload 和 CGI::Uploader 模組則是功能太複雜了,過兩天有時間的話自己動手作一個上傳模組好了。