前回の
シェルコマンドを組み合わせる
(1)
openコマンドを組み合わせる
筆者は普段Macを使用していますが,open
というコマンドがあり,
open
コマンドは,
fooディレクトリのbar.
$ open foo/bar.txt
技術評論社のWebサイトをブラウザで開く
$ open https://gihyo.jp/
system関数を使う
では,open
コマンドをPerlのコードから使うにはどうすればよいでしょうか。
Perlでシェルのコマンドを呼び出す方法はいくつかありますが,system
関数を使っています。
今回のopen
コマンドでは戻り値を使わないので,system
関数で次のように書きます。
system 'open', 'https://gihyo.jp/';
複数のWebサイトを一斉に開く
では次に,for
文,if
文,__
のセットと組み合わせてみましょう。
link-opener.
my @links = <DATA>;
for (@links) {
if ($_ =~ /(https?:\S+)/) {
system 'open', $1;
}
}
__DATA__
https://gihyo.jp/
https://twitter.com/
https://www.google.co.jp/
このコードを実行すると,__
の下に入れたURLのWebページが次々とブラウザで開かれます。
筆者は編集や執筆の仕事をする際,
複数ファイルの行数や文字数をカウントする
件の音楽全集では,
この際,
line-word-count.
use feature 'say';
my @iter = glob "*";
my $line_sum = 0;
my $word_sum = 0;
for (@iter) {
next if (-d "$_");
next unless ($_ =~ /(txt|md)\z/);
my $name = `wc -lm "$_" | awk '{ print \$NF}'` ┓
my $line = `wc -lm "$_" | awk '{ print \$1}'`; |(1)
my $word = `wc -lm "$_" | awk '{ print \$2}'`; ┛
chomp $name;
chomp $line;
chomp $word;
$name =~ s/.*?\/?([^\/]+)\z/$1/;
$word = $word - $line if $line > 1;
$line++;
print "$name =>\tlines: $line\twords: $word";
$line_sum += $line;
$word_sum += $word;
say "";
}
say "";
say "Lines total:\t$line_sum";
say "Words total:\t$word_sum";
コードには,wc
やawk
が含まれています.bashrc
の関数
使い方
では,
.bashrc
alias lwc='perl path/to/line-word-count.pl'
前述の分割したファイルを収めたディレクトリでツールを実行すると,
$ lwc
01_beginning.txt => lines: 74 words: 6943
02_Franz-Schubert.txt => lines: 130 words: 3989
03_Robert-Schumann.txt => lines: 124 words: 5231
04_Frederic-Chopin.txt => lines: 110 words: 4741
05_Franz-Liszt.txt => lines: 59 words: 1774
06_Richard-Wagner.txt => lines: 186 words: 8028
07_Johannes-Brahms.txt => lines: 79 words: 1922
08_Gabriel-Faure.txt => lines: 111 words: 3382
09_Gustav-Mahler.txt => lines: 54 words: 1976
10_Richard-Strauss.txt => lines: 107 words: 2689
11_Pyotr-Tchaikovsky.txt => lines: 77 words: 3509
12_Jean-Sibelius.txt => lines: 61 words: 2011
13_conclusion.txt => lines: 228 words: 9214
Lines total: 1400
Words total: 55409
こうした長丁場の仕事では,
- 注1)
- bashの複数の処理を一つのコマンドで実行できるようにまとめたものです。
- 注2)
- 「ロマン派音楽」
をテーマにした巻だったので, 19世紀のクラシック音楽の作曲家がファイル名に並んでいます。