【PR】

  

Posted by TI-DA at

2011年11月03日

centosにoctaveをインストール

yum install octave


octaveがインストールできません。
表示されるエラーに、「libhdf5.so.0」とあるけど、
hdf5は既にインストールされているし。。。
さて、困った。。。

# yum install octave
Loaded plugins: fastestmirror
Loading mirror speeds from cached hostfile
* base: ftp.iij.ad.jp
* centosplus: ftp.iij.ad.jp
* epel: ftp.iij.ad.jp
* extras: ftp.iij.ad.jp
* updates: ftp.iij.ad.jp
Setting up Install Process
Resolving Dependencies
--> Running transaction check
---> Package octave.i386 6:3.0.5-1.el5 set to be updated
--> Processing Dependency: libhdf5.so.0 for package: octave
--> Finished Dependency Resolution
6:octave-3.0.5-1.el5.i386 from epel has depsolving problems
--> Missing Dependency: libhdf5.so.0 is needed by package 6:octave-3.0.5-1.el5.i386 (epel)
Error: Missing Dependency: libhdf5.so.0 is needed by package 6:octave-3.0.5-1.el5.i386 (epel)
You could try using --skip-broken to work around the problem
You could try running: package-cleanup --problems
package-cleanup --dupes
rpm -Va --nofiles --nodigest




あーだこーだ試した挙句、以下のコマンドで呆気無くインストールできました。

# rpm -e hdf5 hdf5-devel
# yum install octave hdf5 hdf5-devel


hdf5が先に入っていることがまずいみたい。
hdf5を一度アンインストールして、octaveといっしょに再インストールしました。

めでたしめでたし。
^o^)v
  


Posted by kanedayo at 16:41Comments(0)

2011年10月18日

Number::Format 数字の整形と解析

format_number(123456.789); # => 123,456.79
unformat_number('987,654.321'); # => 987654.321

見たいな使い方ができるみたい。


例のごとくインストールされていないので、インストールから。

sudo cpan Number::Format



使い方は、関数っぽく使う方法と、
オブジェクトっぽく扱う方法が用意されているようだけど、
関数っぽい使い方は、用意された変数を変えても動作しないみたい。

#!/usr/bin/perl -l
use strict;
use warnings;

use Number::Format;
my $x = new Number::Format;
print $x->format_number(123456.789); # => 123,456.79 # デフォルトで有効数字2桁
print $x->unformat_number('987,654.321'); # => 987654.321

print "========";

use Number::Format qw(:subs :vars);
$THOUSANDS_SEP = '+'; # 変更しても反映されない??
$DECIMAL_POINT = '.';
$INT_CURR_SYMBOL = 'yen';
$DECIMAL_DIGITS = 5;
print format_number(123456.789);
print unformat_number('987,654.321');

  


Posted by kanedayo at 23:07Comments(0)

2011年10月11日

WWW::MechanizeがContent-Typeを無視している?

$mech->content()
$mech->save_content('file.html')


出力がブラウザで正しく表示されない?
コンテンツ内の'Content-Type'にかかわらず、「utf8」で出力している気がする。


ヘッダより、エンコード文字を取得する方法。
その他、いろいろ試すも、効果がありません。。。。

my $res=$mech->get('http://kakaku.com');
my $ct = $res->headers->header('Content-Type');
$mech->delete_header('Content-Type');
$mech->add_header('Content-Type'=>'text/html; charset=Shift_JIS');
$mech->content()
$mech->save_content('file.html')


さぁ~、どうしよう、、、、
><)/~  


Posted by kanedayo at 01:57Comments(2)

2011年10月09日

Getopt::Long コマンドラインオプションの操作

■Getopt::Long

○コマンドラインからデフォルトを上書き。

use Getopt::Long;
my $v = 0; # フラッグ
my @name = ""; # 配列
GetOptions('verbose'=>\$v, 'name=s'=>\@name);
print "v=$v\n";
print "n=@name\n";
# ./test.pl -v -n foo -n bar



○ハッシュに詰める

use Getopt::Long;
my %opt = (verbose=>0, name=>"hoge");
GetOptions(\%opt, qw/ verbose name=s / );
print "v=$opt{verbose}\n";
print "n=$opt{name}\n";
# ./test.pl -v -n foo -n bar



■App::Option

Getopt::Longと違い、
「設定ファイル」
「環境変数」
「コマンドライン」

から変数を定義することができる。  


Posted by kanedayo at 12:58Comments(0)

2011年10月04日

Bundle::CPAN

「perl -de 0」や「perl -MCPAN -e shell」や「scraper」で補完機能をが使いたくなって。

sudo cpan Bundle::CPAN


「Term::ReadLine::Gnu」ってのもあるようだが、違いが良くわからず。^^;
  


Posted by kanedayo at 23:47Comments(0)

2011年10月03日

vimモードライン

// vim: et:ts=2:sw=2
// vim: et ts=2 sw=2

どちらもOK。↑
でも、こちらはだめでした。↓
//vim: et:ts=2:sw=2
//vim: et ts=2 sw=2


違いは、「//」と「vim:」の間のスペース。
少しハマったぜ。
><)/  


Posted by kanedayo at 23:27Comments(0)

2011年09月20日

Config::Tiny ini形式の操作

いつものように、標準では入ってないので、インストール。
インストール後、perldocで使い方を確認。

sudo cpan Config::Tiny
perldoc Config::Tiny



.ini形式のファイルを読み込むモジュール。
init形式とは、以下のようなもの。
[section]
val1=val
val2=val


「#」と「;」はコメント。
コメントやスペース、順序は維持されない。
これらを考慮するときは、
「Config::Simple」や「Config::General」などがあるようだ。


perldocをまねて、簡単なコードを書いてみた~^o^)v
use strict;
use warnings;

use Config::Tiny;

my $Config = Config::Tiny->new;

$Config = Config::Tiny->read('file.ini'); # ファイルの読み込み

my $val = $Config->{section1}->{val}; # 値の読み込み

delete $Config->{section1}->{"para$val"}; # プロパティの削除

$val++;
$Config->{section1}->{val}= $val; # プロパティがあれば、値の上書き
$Config->{section1}->{"para$val"} = $val; # プロパティがなければ、追加

$Config->write('file.ini');


  


Posted by kanedayo at 01:05Comments(0)

2011年09月14日

Time::Piece 日付と時間の操作

時間に対して、
printfやscanfみたいなことができるみたいです。

いろいろできるモジュールですが、
このブログがまとめられてて、わかりやすかったです。^^)v
「Time::Piece -日付と時刻を扱う@サンプルコードによるPerl入門」
http://d.hatena.ne.jp/perlcodesample/20091105/1246274997  


Posted by kanedayo at 23:17Comments(0)

2011年09月11日

Text::CSV CSVの操作

CSV:Comma Separated Values : 区切り文字がコンマ
TSV:Tab Separated Values : 区切り文字がタブ

CSVよりTSVが便利そう。
CSVはセル内にコンマがあると扱いが難しい。
セル内にタブを使うことはない(?)から、TSVが楽かな。
ExcelからのコピペもTSVのようだし。

my @fields = split /,/, $line; # NG! セル内にコンマがあると使えない
my @fields = split /\t/, $line; # NG! 一般的にセル内にタブは使わない(?)



ただし、CSVもTSVも、一行ずつ処理する際に、改行を含むセルの扱いが難しい。
なので、PerlでCSVを使うときは、素直に「Text::CSV」を利用する。

PerlでCVSを使うには、このあたりかな。
Text::CSV (あればXS、なければPPを使う)
Text::CSV_PP (Pure Perl)
Text::CSV_XS (高速)
Text::CSV::Simple


ますは、インストール。

$ sudo cpan Text::CSV Text::CSV_XS Text::CSV::Simple



perldocから:

Embedded newlines
Unicode (UTF8)
FUNCTIONS
DIAGNOSTICS



わかりやすいサンプルコードがあるのでそのまま記載。

use Text::CSV;

my @rows;
open my $fh, "<:encoding(utf8)", "test.csv" or die "test.csv: $!";
while ( my $row = $csv->getline( $fh ) ) {
$row->[2] =~ m/pattern/ or next; # 3rd field should match
push @rows, $row;
}
$csv->eof or $csv->error_diag();
close $fh;

$csv->eol ("\r\n");

open $fh, ">:encoding(utf8)", "new.csv" or die "new.csv: $!";
$csv->print ($fh, $_) for @rows;
close $fh or die "new.csv: $!";





デフォルトでは、ASCIIしか扱えない、
セル内に改行など含む場合は、「binary=>1」を設定する。

改行の扱いで失敗する例:

my $csv = Text::CSV->new ({ binary => 1, eol => $/ });
while (<>) { # これだと、改行を含むセルが崩れる。
$csv->parse ($_);
my @fields = $csv->fields ();



良い例:

my $csv = Text::CSV->new ({ binary => 1, eol => $/ });
while (my $row = $csv->getline (*ARGV)) {
my @fields = @$row;


あるいは、perl5.6以上だと次の書き方がより安全。

my $csv = Text::CSV->new ({ binary => 1, eol => $/ });
open my $io, "<", $file or die "$file: $!";
while (my $row = $csv->getline ($io)) {
my @fields = @$row;



データ型を定義したいときは、「types」を使う。

$csv->types ([Text::CSV::IV (), # integer
Text::CSV::NV (), # numeric/float
Text::CSV::PV ()]); # string

$csv->types (undef); # リセット
$types = $csv->types (); # 現在の設定を取得

# IV Set field type to integer.
# NV Set field type to numeric/float.
# PV Set field type to string.


  


Posted by kanedayo at 23:56Comments(0)

2011年09月11日

CPANの読み方と意味

「CPAN」
読み方:しーぱん

Comprehensive Perl Archive Network
包括的なパールアーカイブネットワーク

直訳。。(^_^;
  


Posted by kanedayo at 20:28Comments(0)

2011年09月11日

YAML::Shell YAMLのテスト用シェル

yshが入ってなかったのでインストール
$ sudo cpan YAML::Shell


perldoc によると、基本的な使い方は以下のとおり。
cat yaml.file | ysh | less


$ cat - | ysh
---
- 1
- 2
- 3
Ctrl-D
$VAR1 = [
'1',
'2',
'3'
];


ysh単体でシェルとして使用する場合は、こんな感じ。
(ブラウザで表示するとインデントが崩れている。。涙)

ysh > ---
yaml> - 1
yaml> - 2
yaml> - 3
yaml> ...
ysh > [ 1 2 3 ]
ysh > ;
perl> @i=val;
perl> for($i=0;$i<3;$i++){
perl> @i={key=>@i};
perl> }
perl> ;
--- ''
ysh > @i
---
key:
key:
key: val
ysh > (@i,@i)
---
key:
key:
key: val
---
key:
key:
key: val
ysh > [@i,@i]
---
- &1
key:
key:
key: val
- *1


  


Posted by kanedayo at 19:39Comments(0)

2011年09月11日

FindBin スクリプトの場所を取得

perldoc FindBin より

use FindBin;
use lib "$FindBin::Bin/../lib"
# or
use FindBin qw($Bin);
use lib "$Bin/../lib";




使い方は、いたってシンプル。

#!/usr/bin/perl -l

use FindBin qw($Bin $Script);

use lib "$Bin/../lib";
foreach (@INC) {print};

print $Bin;
print $Script;

  


Posted by kanedayo at 06:00Comments(0)

2011年09月11日

Perl::Tidy ソースコードの整形

Perlのソースコードを整形

sudo cpan -i Perl::Tidy


なかったのでインストール。

perldoc Perl::Tidy より

EXAMPLE
Using the formatter Callback Object


perldoc perltidy すると、読みきれないくらいのオプションが閲覧できます。

基本的な使い方。シンプル~^o^)v

use Perl::Tidy;
Perl::Tidy::perltidy();




perltidyというコマンドが便利かも。

perltidy filename.pl
diff filename.pl filename.pl.tdy

  


Posted by kanedayo at 00:42Comments(0)

2011年09月11日

lib @INCの操作

コンパイル時に@INCを操作する

perldoc lib より

Adding directories to @INC
Deleting directories from @INC
Restoring original @INC


以下の二つは、ほとんど同じだけど、「use lib」は、アーキテクチャ依存のパスも探してくれてるそうな。
use lib LIST;
BEGIN { unshift(@INC, LIST) }


no lib LIST;

とすると、取り除くこともできる。

@INC = @lib::ORIG_INC;

とすると、デフォルトに戻る。  


Posted by kanedayo at 00:08Comments(0)

2011年09月10日

Encode 文字コード操作

perldoc Encode より

PERL ENCODING API
Listing available encodings
Defining Aliases
Finding IANA Charactor Set Registry names
Encoding via PerlIO
Handling Malformed Data
Defining Encodings
The UTF-8 flag
UTF-8 vs. utf8



オブジェクトを作って利用すると動作が早くなるようだ。

my $enc = find_encoding("shiftjis");
while(<>) {
my $utf8 = $enc->decode($_);
... # now do something with $utf8;
}




文字コードの変換

from_to($data, "sfhitjis", "euc-jp");




利用可能なコードのリスト

@list = Encode->encodings();
@list = Encode->encodings(":all");
@list = Encode->encodings("JP");




エイリアスの定義

use Encode::Alias;
define_alias("NEWCODE" => "shiftjis");
$octets = encode("NEWCODE",$str);




PerlIOを用いた自動変換。これ便利かも。

### Version 1 via PerlIO
open(INPUT, "< :encoding(shiftjis)", $infile)
|| die "Can't open < $infile for reading: $!";
open(OUTPUT, "> :encoding(euc-jp)", $outfile)
|| die "Can't open > $output for writing: $!";
while (<INPUT>) { # auto decodes $_
print OUTPUT; # auto encodes $_
}
close(INPUT) || die "can't close $infile: $!";
close(OUTPUT) || die "can't close $outfile: $!";




utf8とUTF-8は違うらしい。

encode("utf8", "\x{FFFF_FFFF}", 1); # okay
encode("UTF-8", "\x{FFFF_FFFF}", 1); # croaks

  


Posted by kanedayo at 23:49Comments(0)

2011年09月10日

CPANモジュールのインストール

以下のどちらかでOK。前者が楽かな。
sudoしてないと、最後でこけます~泣

$ sudo cpan [モジュール名]
$ sudo perl -MCPAN -e shell
cpan > install [モジュール名]

  


Posted by kanedayo at 22:04Comments(0)

2011年09月10日

CPAN shellを初めて起動したときのログ

CPANのshellを最初に起動したときのログ~^o^)v

以下のどちらかでOK。
インストール作業を続けるときは、sudoしてないと、最後でこけます~泣
$ sudo cpan
$ sudo perl -MCPAN -e shell


以下は、一般ユーザで起動してみたときのログです。
[kanedayo@localhost ~]$ perl -MCPAN -e shell

/home/kanedayo/.cpan/CPAN/MyConfig.pm initialized.


CPAN is the world-wide archive of perl resources. It consists of about
100 sites that all replicate the same contents all around the globe.
Many countries have at least one CPAN site already. The resources
found on CPAN are easily accessible with the CPAN.pm module. If you
want to use CPAN.pm, you have to configure it properly.

If you do not want to enter a dialog now, you can answer 'no' to this
question and I'll try to autoconfigure. (Note: you can revisit this
dialog anytime later by typing 'o conf init' at the cpan prompt.)

Are you ready for manual configuration? [yes]


The following questions are intended to help you with the
configuration. The CPAN module needs a directory of its own to cache
important index files and maybe keep a temporary mirror of CPAN files.
This may be a site-wide directory or a personal directory.



I see you already have a directory
/home/kanedayo/.cpan
Shall we use it as the general CPAN build and cache directory?

CPAN build and cache directory? [/home/kanedayo/.cpan]


If you want, I can keep the source files after a build in the cpan
home directory. If you choose so then future builds will take the
files from there. If you don't want to keep them, answer 0 to the
next question.



How big should the disk cache be for keeping the build directories
with all the intermediate files?

Cache size for build directory (in MB)? [10]


By default, each time the CPAN module is started, cache scanning
is performed to keep the cache size in sync. To prevent from this,
disable the cache scanning with 'never'.

Perform cache scanning (atstart or never)? [atstart]


To considerably speed up the initial CPAN shell startup, it is
possible to use Storable to create a cache of metadata. If Storable
is not available, the normal index mechanism will be used.

Cache metadata (yes/no)? [yes]


The next option deals with the charset your terminal supports. In
general CPAN is English speaking territory, thus the charset does not
matter much, but some of the aliens out there who upload their
software to CPAN bear names that are outside the ASCII range. If your
terminal supports UTF-8, you say no to the next question, if it
supports ISO-8859-1 (also known as LATIN1) then you say yes, and if it
supports neither nor, your answer does not matter, you will not be
able to read the names of some authors anyway. If you answer no, names
will be output in UTF-8.

Your terminal expects ISO-8859-1 (yes/no)? [yes]


If you have one of the readline packages (Term::ReadLine::Perl,
Term::ReadLine::Gnu, possibly others) installed, the interactive CPAN
shell will have history support. The next two questions deal with the
filename of the history file and with its size. If you do not want to
set this variable, please hit SPACE RETURN to the following question.

File to save your history? [/home/kanedayo/.cpan/histfile]
Number of lines to save? [100]


The CPAN module can detect when a module that which you are trying to
build depends on prerequisites. If this happens, it can build the
prerequisites for you automatically ('follow'), ask you for
confirmation ('ask'), or just ignore them ('ignore'). Please set your
policy to one of the three values.

Policy on building prerequisites (follow, ask or ignore)? [ask]


The CPAN module will need a few external programs to work properly.
Please correct me, if I guess the wrong path for a program. Don't
panic if you do not have some of them, just press ENTER for those. To
disable the use of a download program, you can type a space followed
by ENTER.

Where is your gzip program? [//img02.ti-da.net/usr/bin/gzip]
Where is your tar program? [/bin/tar]
Where is your unzip program? [//img02.ti-da.net/usr/bin/unzip]
Where is your make program? [//img02.ti-da.net/usr/bin/make]
Warning: links not found in PATH
Where is your links program? []
Where is your wget program? [//img02.ti-da.net/usr/bin/wget]
Warning: ncftpget not found in PATH
Where is your ncftpget program? []
Warning: ncftp not found in PATH
Where is your ncftp program? []
Where is your ftp program? [//img02.ti-da.net/usr/kerberos/bin/ftp]
Where is your gpg program? [//img02.ti-da.net/usr/bin/gpg]
What is your favorite pager program? [//img02.ti-da.net/usr/bin/less]
What is your favorite shell? [/bin/bash]


Every Makefile.PL is run by perl in a separate process. Likewise we
run 'make' and 'make install' in processes. If you have any
parameters (e.g. PREFIX, LIB, UNINST or the like) you want to pass
to the calls, please specify them here.

If you don't understand this question, just press ENTER.

Parameters for the 'perl Makefile.PL' command?
Typical frequently used settings:

PREFIX=~/perl non-root users (please see manual for more hints)

Your choice: []
Parameters for the 'make' command?
Typical frequently used setting:

-j3 dual processor system

Your choice: []
Parameters for the 'make install' command?
Typical frequently used setting:

UNINST=1 to always uninstall potentially conflicting files

Your choice: []


Sometimes you may wish to leave the processes run by CPAN alone
without caring about them. As sometimes the Makefile.PL contains
question you're expected to answer, you can set a timer that will
kill a 'perl Makefile.PL' process after the specified time in seconds.

If you set this value to 0, these processes will wait forever. This is
the default and recommended setting.

Timeout for inactivity during Makefile.PL? [0]


If you're accessing the net via proxies, you can specify them in the
CPAN configuration or via environment variables. The variable in
the $CPAN::Config takes precedence.

Your ftp_proxy?
Your http_proxy?
Your no_proxy?
You have no /home/kanedayo/.cpan/sources/MIRRORED.BY
I'm trying to fetch one
LWP not available
CPAN: Net::FTP loaded ok
Fetching with Net::FTP:
ftp://ftp.perl.org/pub/CPAN/MIRRORED.BY


Now we need to know where your favorite CPAN sites are located. Push
a few sites onto the array (just in case the first on the array won't
work). If you are mirroring CPAN to your local workstation, specify a
file: URL.

First, pick a nearby continent and country (you can pick several of
each, separated by spaces, or none if you just want to keep your
existing selections). Then, you will be presented with a list of URLs
of CPAN mirrors in the countries you selected, along with previously
selected URLs. Select some of those URLs, or just keep the old list.
Finally, you will be prompted for any extra URLs -- file:, ftp:, or
http: -- that host a CPAN mirror.

(1) Africa
(2) Asia
(3) Central America
(4) Europe
(5) North America
(6) Oceania
(7) South America
Select your continent (or several nearby continents) [] 2
Sorry! since you don't have any existing picks, you must make a
geographic selection.

(1) China
(2) Hong Kong
(3) India
(4) Indonesia
(5) Israel
(6) Japan
(7) Kazakhstan
(8) Pakistan
(9) Republic of Korea
(10) Russia
(11) Saudi Arabia
(12) Singapore
(13) Taiwan
(14) Thailand
(15) Turkey
Select your country (or several nearby countries) [] 6
Sorry! since you don't have any existing picks, you must make a
geographic selection.

(1) ftp://ftp.dti.ad.jp/pub/lang/CPAN/
(2) ftp://ftp.jaist.ac.jp/pub/CPAN/
(3) ftp://ftp.kddilabs.jp/CPAN/
(4) ftp://ftp.nara.wide.ad.jp/pub/CPAN/
(5) ftp://ftp.riken.jp/lang/CPAN/
(6) ftp://ftp.ring.gr.jp/pub/lang/perl/CPAN/
(7) ftp://ftp.u-aizu.ac.jp/pub/CPAN/
(8) ftp://ftp.yz.yamagata-u.ac.jp/pub/lang/cpan/
Select as many URLs as you like (by number),
put them on one line, separated by blanks, e.g. '1 4 5' [] 2 3 5

Enter another URL or RETURN to quit: []
New set of picks:
ftp://ftp.jaist.ac.jp/pub/CPAN/
ftp://ftp.kddilabs.jp/CPAN/
ftp://ftp.riken.jp/lang/CPAN/


commit: wrote /home/kanedayo/.cpan/CPAN/MyConfig.pm
Terminal does not support AddHistory.

cpan shell -- CPAN exploration and modules installation (v1.7602)
ReadLine support available (try 'install Bundle::CPAN')

cpan>

  


Posted by kanedayo at 21:00Comments(0)

2011年09月10日

モジュールの確認方法

調べたこと~まとめ~^o^)v

インストールされているCPANモジュールの確認方法

以下のようにすると、@INC以下のモジュール(*.pm)がダーーーっと出力される。
$ find `perl -e 'print "@INC"'` -name '*.pm' -print


以下のようにすると、実際にロードできるか確かめることができる。
エラーが出ずに動けばOKみたい。
$ perl -MGetopt::Long -e ''
$ perl -MGetopt::Long -le 'print $Getopt::Long::VERSION'


インストールされていれば、ドキュメントを表示して確認するでもOKかな。
$ perldoc Getopt::Long


インストールされたパスを知るには、「-m」オプションで。
$ perldoc -ml Getopt::Long
/usr/lib/perl5/5.8.8/Getopt/Long.pm

  


Posted by kanedayo at 19:45Comments(0)

2011年09月04日

textareaタグ代替案

コードの載せ方を悩んでいましたが、いろんな方のブログをみてて
スタイルシートを編集すると、pタグとblockquoteタグがいい感じになりました。
ひとまずこれでいいかな。
^o^)v


#!/usr/bin/perl
use strict;
use warning;
# なが~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~いコメント



#!/usr/bin/perl
use strict;
use warning;
# なが~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~いコメント

  


Posted by kanedayo at 01:14Comments(0)

2011年09月03日

textareaタグ 使えない~涙

なんとなくわかったこと。
ブログの構成として、textareaはコメント欄を表示する部位でのみ、使用していることを想定しているようだ。表示の過程でtextareaをspanで囲む処理が発生するようなのですが、
ここで、textareaが想定以上あると、spanで囲む処理が思わぬ動作をするようです。

spanで囲む処理は、こちらではどうしようもないっぽく、つまりは、textareaは使えないってことかな。  


Posted by kanedayo at 21:12Comments(2)