Perl

Perl ベストプラクティス 気になったもの

3.1. Identifiers Use grammatical templates when forming identifiers. 4.5. Constants Use named constants, but don't use constant. 4.10. Heredoc Indentation Use a "theredoc" when a heredoc would compromise your indentation. 4.18. List Member…

関数を作り出す関数...それが高階関数

# curry.pl sub curry { my $func = shift; my @capture_arg = @_; return sub { return $func->(@capture_arg, @_); } } my $for_print = sub { print "@_\n"; }; my $printer = curry($for_print, "Hello,"); # 引数をキャプチャする $printer->("world!")…

Shift()でサブルーチン

# ref6.pl sub hellofunc { my $func = shift; return $func->("Hello!"); } hellofunc( sub { print "@_\n"; } ); # (1) hellofunc( sub { print "@_ World!\n"; } ); # (2) my $decorator = sub { return "***" . shift() . "***"; #shift()で受け取ったコ…

クロージャ

sub newprint { my $x = shift; return sub { my $y = shift; print "$x, $y!\n"; }; } $h = newprint("Howdy"); $g = newprint("Greetings"); # Time passes... &$h("world"); &$g("earthlings"); 出力はこうなります。 Howdy, world! Greetings, earthling…

Treebuilder utf8対策済み

#!/usr/bin/env perl use strict; use warnings; use utf8; use Encode; use HTML::TreeBuilder; binmode STDOUT, ':encoding(cp932)'; binmode STDERR, ':encoding(cp932)'; #use encoding "cp932"; my $html=<<'HTML'; <html> <head> <title>Test Page</title> </head> <body> <div id="content"> <h1>Test Page</h1> </div></body></html>

"cancelled"文字列が存在する行をスルーしてファイル読み込みする。

while(<IN>){ chomp; next if($_ =~/cancelled/); #イコールとチルダを離してはダメ! print OUT $_."\n";</in>

WWW::Mechanize とりあえず完成!

use strict; use warnings; use WWW::Mechanize; use HTML::TreeBuilder; use utf8; use Encode; binmode STDOUT, ':utf8'; sub say {print @_, "\n";} open(IN, '<:encoding(utf8)', 'word_list.txt'); open(OUT, ">word_list_output.txt"); while(<IN>){ chomp; my ($word) = split(/,/, $_); #split リストコン</in></:encoding(utf8)',>…

ファイル入力用のutf8 設定 と リテラル設定

use utf8; binmode STDOUT, ':utf8'; #出口用の追加設定 open my $fh, '<:encoding(utf8)', 'data.txt' #入り口用設定 or die "failed to open file: $!"; my $text = <$fh>; my @text = split //, $text; for (@text) { say $_; } close $fh; ########################################################## use utf8; binmode STDOUT, ':u…</:encoding(utf8)',>

CSV流し込み ハッシュによるtempメモリー

my %data = (); open(IN, 'customer_data_win2.csv'); while(<IN>){ chomp; my ($id, $name, $age, $ken, $shi) = split(/,/, $_); # 人データを作る my $people = [$id, $name, $age]; # 結果配列に保存する push(@{$data{$ken}{$shi}}, $people); }</in>

コード一気に読み込む Slurpモジュールでも同じ

my $text = do {local $/; <$fh>;}; my $text = do {local $/ = undef; #改行デリミタをリセット <$fh>; };