Smart

For Professional Web Designers and Developers

MENU

Perlクイックリファレンス

2009年6月5日 49 COMMENTS

1.文字列の出力

文字列を出力するには、print関数を使います。

print "Hellow world!\n";
>Hellow world!

出力文は、カンマ( , )で区切ることもできます。

print "Hellow world!", "\n";
> Hellow world!

2.変数と代入演算子

計算した結果を変数に代入することもできます。

$x = 10 + 3 -1; # $x は「12」

+ や - などの記号を『演算子』といい、特に上記のような計算に使う演算子を『算術演算子』と言います。

Perl の変数には、スカラ変数、配列変数、ハッシュ変数というデータ型があります。変数のデータ型は変数名の前に付く1文字で区別されます。スカラ変数の場合はダラー( $ )、配列変数はアットマーク( @ ) 、ハッシュはパーセント( % )が変数の先頭に付きます。

文字 意味
スカラ $ $value 1つの変数で1つの値を記録します。
配列 @ @value 配列はスカラ変数のリストです。個々のスカラには、0から始まる数字のインデックスを使ってアクセスすることができます。
ハッシュ % %value ハッシュは、複数のスカラをキーと値のペアによって格納する変数です。配列とは違って順番がなく、キーを指定して個々のスカラにアクセスします。
型グロブ * *glob glob という名前を持つ変数すべてを意味します。

変数は以下のように値を代入したり出力することができます。

# 変数に文字列を代入
$value = "テストです";
# 変数を出力
print $value;
【参照ページ】

配列

複数の値を1つの変数で管理したい場合は、『配列』という変数が最適です。

配列を初期化する場合は、要素をカッコで囲み、各要素毎にカンマで区切ります。

@week = ('日曜', '月曜', '火曜', '水曜',
'木曜', '金曜', '土曜');

配列はインデックスを使って参照します。インデックスは 0から始まるので注意してください。たとえば1番目のデータ "日曜" を呼び出すときは、$week[0]、"月曜"なら $week[1] とします。

# 配列 @week の1番目の要素を表示
print $week[0], "\n";
> 日曜
# 配列 @week の2番目の要素を表示
print $week[1], "\n";
> 月曜
【参照ページ】

ハッシュ

配列と同じように、関連ある複数のデータをまとめて扱うことのできる変数があります。それが『ハッシュ』です。配列はインデックスで値を管理していましたが、ハッシュはキーで値を管理します。配列と比べたときのハッシュの利点は、キーで値を管理できるので、可読性が高くなることにあります。

%week = (
	'Sun' => '日曜',
	'Mon' => '月曜',
	'Tue' => '火曜',
	'Wed' => '水曜',
	'Thu' => '木曜',
	'Fri' => '金曜',
	'Sat' => '土曜',
);

配列では、[ ] でインデックスを囲みましたが、ハッシュは、 { } でキーを囲みます。

print $week{'Sun'};
> 日曜
【参照ページ】

3.式と項

****

4.制御文の使い方

条件文

「もし~ならば、・・・を実行する」という条件つき命令は、プログラムの流れを制御するときによく利用されます。

次の使用例は、変数の値によってメッセージを変えています。

if ( $var eq 'A' ) {
	print "Aです";
} elsif ( $var eq 'B' ) {
	print "Bです";
} else {
	print "AでもBでもない";
}

ループ文

配列の値すべてに処理したいとき、foreach が便利です。foreachは、リストの1番目から順番に変数に代入していき、ブロックを実行します。リストが終了した時点で繰り返しが終了されます。

@week = ('Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat');
foreach $value( @week ) {
  print $value, "\n";
}
> Sun
> Mon
> Tue
> Wed
> Thu
> Fri
> Sat
【参照ページ】

5.ファイル入出力

ファイルを読み込むには open 関数を使います。open 関数の引数には、ファイルハンドルとファイルパスを渡します。

# 読込用にファイルを開く
open FH, "< filename.txt";

ファイルの1行目を読み込むには、ファイルハンドルを利用して次のように記述します。

$in_line = <FH>;

すべての行を読み込んだり出力するには、while 文を使います。

構文

while (条件式) { 真のとき繰り返す }

条件式が真の間、ブロックを実行します。判定はループの最初に行われます。ループの間条件が決してFALSEにならない場合、命令が永遠に実行されます。

入力「<>」を while(<>) のように使うと、特殊変数 $_に読み込んだ行が入るようになっています。

open( DAT, "test.dat" );
while ( <DAT> ) { # "test.dat"を1行ずつ読み、出力する
    print $_, "\n";
}
close( DAT );

ファイルを出力したい場合は、読み込むときと少し勝手が違います。読み込む際はファイル名の前に <という記号をつけていましたが、書込みの場合は > という記号をつけます。

# 書込み用にファイルを開く
open FH, "> filename.txt";
# データを出力
print FH $line;
close( FH );
【参照ページ】

当然のことですが、ファイルを扱う際には、ファイルにしかるべきパーミッションが設定されている必要があります。

ファイルの読み書きをする際の手順は下記のとおりです。

  1. ファイルを開く(open)
  2. ファイルの内容を読みこむ/ファイルに書き込む(print など)
  3. ファイルを閉じる(close)

openの際に、ファイルに対するアクセスの種類を決定します。具体的には、読み込みだけなのか、ファイル末尾に書き込むのか、ファイルを新規に作成してから書き込むのか、などです。openの第二引数がその指定です。詳しくは perldocやリファレンスを見ていただきたいのですが、下の例では、読み込みだけ( "<ファイル名" ) で openしています。

下の例は、UNIX コマンドの catのように、あるファイルの内容を行番号をつけて表示するプログラムです。複数のファイルが指定されれば、それらを次々に表示します。

ファイルの読み込み

foreach $fname ( @ARGV ) {
	print "--------- $fname ---------\n";
	open FP, "<$fname" or die "File Open Error.\n";
	while( <FP> ) {
		$counter++;
		print "$counter : $_\n";
	}
	close FP;
	counter = 0;
}

foreach ループでコマンドラインから引数で与えられたファイル名を取り出し、 whileループで、ファイルの内容を一行ずつ取り出し、すべての行を読み終えるまで処理しています。この while書き方は常套句なので、覚えておきましょう。$_ に、そのとき処理中の一行がそのまま入っています。

ファイルの書き込み

ファイルに書き込む際には、追記モード('>>ファイル名')と新規モード('>ファイル名')があることを知らねばなりません。

詳しくは関数リファレンスの open の項をご参照願いたいのですが、新規モードにすると、openの前にファイルに書き込まれていた内容は消去されてしまいます。
追記モードは既存のファイルに追加して書き込んでいく際に使われます。普通にすればファイルの末尾に書かれていきます。

以下、$dataというリストの内容をファイルに書き出していくサンプルです。ここでは新規モードでファイルをオープンしています。

open FP, ">/tmp/hoge.txt" or die
"Can't Open File.\n";
foreach $item (@data) {
	print FP $item . "\n";
}
close FP;

6.サブルーチンの作成と使用法

サブルーチンとは、決まった処理をプログラムの別のところに記述しておき、使う際にパラメータを渡したりすることができます。また、サブルーチンからサブルーチン内で処理した結果の値を関数の呼び出し元に返すことができます。それをサブルーチンの戻り値(返り値)といいます。

サブルーチンの宣言は下記のようにします。

sub func_test {
  my ($arg1, $arg2) = @_;
  return $arg1 + $arg2;
}

2 行目の代入文は、配列 @_ の内容を、順に $arg1 と $arg2にそれぞれ代入する、という意味です。この 2 行目の時点では、@_には、引数のリストが入っています。

サブルーチンを呼び出すときは、下記のようにします。

$sum = func_test(1, 2);

上記の結果は、$sumに 1 + 2 の結果、3 が代入されます。
 

49 Comments

  1. Pingback: PerlでClass::DBI::mysqlの文字化けを回避する方法

  2. " An auditor is a person trained and qualified in applying auditing to individuals for th . Of course, the most effective teaching tools are the ones that make time-telling lessons a fun and adventurous journey through the hours and minutes of the day.. nike free 3.0 v2 That modification method offers a bonus towards man or women because they are now able to set up their very own style which often they will generally were going to get about its ..
    The Shox BB Basketball shoe is available in any color made by the company, as it is a Nike iD candidate. nike free run shoes christmas loans immediate cash support for xmas nike free run shoes The restaurant also provides a separate bar area for a more relaxed dining experience and includes several varieties of martinis, a large selection of coffees and Ethiopian wines that are made from fermented honey.
    Then insert a dowel of the proper size (it could be wood or metal) with some glue before bringing both parts together and gluing once more. nike roshe run ireland watch sylvania 300 live stream nascar richmond virginia 2010 race online free nike free 3.0 v4 fantastic nike air jordan assistance for effectively improving your nutrition nike free 3.0 v4 ireland The Parrish Art Museum is 17 miles from The Inn, and the Southampton Historical Museum is 17.5 miles away..

  3. Thanks for your marvelous posting! I really enjoyed reading it, you will be a great author.

    I will be sure to bookmark your blog and may come back in the future.
    I want to encourage you to definitely continue your great posts, have a nice morning!

  4. Thanks on your marvelous posting! I certainly enjoyed reading it, you can be a great author.
    I will remember to bookmark your blog and will come
    back sometime soon. I want to encourage yourself to continue your great posts, have a nice afternoon!

  5. I'm truly enjoying the design and layout of your website. It's a very easy on
    the eyes which makes it much more enjoyable for me to come here and visit more often.
    Did you hire out a developer to create your theme? Superb work!

  6. I loved as much as you will receive carried out right here.
    The sketch is attractive, your authored material stylish.
    nonetheless, you command get bought an shakiness over that you wish be delivering the following.

    unwell unquestionably come more formerly again as
    exactly the same nearly very often inside case
    you shield this increase.

  7. WOW just what I was looking for. Came here by searching
    for how to remove apps from ipod touch home screen

  8. It is not my first time to pay a quick visit this site, i am browsing
    this web page dailly and get fastidious facts from here daily.

  9. Deer For Sale including the top Deer Breeding of Whitetail Does, Breeder Bucks, Shooter Bucks and Fawns for sale
    from the top Deer Breeders!

  10. Have you ever considered publishing an ebook or guest authoring on other blogs?
    I have a blog based upon on the same ideas
    you discuss and would really like to have you share some stories/information.
    I know my subscribers would appreciate your work. If you are even
    remotely interested, feel free to shoot me an email.

  11. Hi there to all, how is everything, I think every one is
    getting more from this site, and your views are pleasant for new
    users.

  12. Thanks for every other informative web site. Where else
    may just I am getting that kind of information written in
    such an ideal way? I have a venture that I am simply
    now working on, and I've been on the look out for such information.

  13. Thanks for ones marvelous posting! I really enjoyed reading it,
    you may be a great author.I will be sure to bookmark your blog and definitely will come back very soon.
    I want to encourage yourself to continue your great writing,
    have a nice morning!

  14. You ought to take part in a contest for one of the best websites on the net.
    I am going to highly recommend this web site!

  15. whoah this blog is excellent i love reading your posts.
    Stay up the great work! You recognize, lots of people are hunting around for this info, you can help
    them greatly.

  16. Good day! Do you know if they make any plugins to assist with SEO?
    I'm trying to get my blog to rank for some targeted keywords but I'm not seeing very good gains.
    If you know of any please share. Kudos!

  17. A renter never needs to worry about spending a big chunk to cover this.
    • no financial institution or even finance company participation.

    If you are forced to evict him or her, you have to invest time and effort and may incur other expenses such as legal fees or court costs.

  18. It's perfect time to make a few plans for the longer term and it is time to be happy. I've read this submit and if I could I desire to recommend you some
    attention-grabbing things or advice. Perhaps you can write next articles regarding this article.
    I desire to read even more things about it!

  19. Thanks for finally writing about >Perlクイックリファレンス | Smart -Web Magazine
    <Liked it!

  20. Interesting blog! Is your theme custom made or did you download it from somewhere?
    A design like yours with a few simple tweeks would really make my blog jump out.
    Please let me know where you got your theme. Thanks a
    lot

  21. See call for out of pouch disbursals? Happen more
    than please draw eccentric of physical exertion and frequency.
    This is based in Punjab and mostly referees our clients in reality told that!

  22. It's in fact very difficult in this active life to listen news on TV, so I just use world wide web for that reason, and obtain the most up-to-date news.

  23. Nice post. I learn something totally new and challenging on sites I stumbleupon everyday.
    It's always interesting to read through articles from other authors and practice a little something from other web sites.

  24. great blog I am a huge Wrestling viewer from Holland

  25. There are several other ways to acquire these free codes online.

    We hope that you will act in a responsible manner
    with this kind of information at your finger tips. When Sony released
    Play - Station three, it came with this complete new issue.

  26. I think this is one of the most vital info
    for me. And i'm glad reading your article. But wanna remark on some general things, The site style is great, the articles is really excellent : D. Good job, cheers

  27. It wasn't as a consequence of my 'advanced' age that my ankle broke,' Jeter
    stated in an attempt to quiet his critics. I think after going
    through 15 years of getting a unblemished image, why do you
    put a black mark at the end. "My problem is actually that they don't overcome tired, " director
    May well Girardi says.

  28. Right away I am ready to do my breakfast, when having my breakfast coming again to read more news.

  29. Hi, just wanted to mention, I loved this blog post.
    It was practical. Keep on posting!

  30. Once you take it to the shop, make sure you get
    it in writing what the mechanics are going to do to improve
    the car's overall performance with complete service and labor costs in writing. The automotive industry has suffered tremendously financially, both in the manufacturing sector and in the dealerships used to promote their vehicles. It's also recommended to talk
    about the whole automobile repair plan together with your mechanic prior to start to avoid any unexpected large auto repair bill.
    For shops that merely carry out diagnostic work and also don't offer parts, they ought to have the capacity to present you with an unbiased viewpoint on what repairs are required. Free of expense services persuades the people today to use them unintentionally. When it comes to fixing something on your car, the prices can sometimes be high, but there are some easy auto repair projects you can do yourself.

  31. Remarkable! Its really remarkable article, I have got much
    clear idea concerning from this post.

  32. Hello to every one, as I am genuinely eager of reading this blog's post to be updated on a regular basis. It consists of pleasant data.

  33. Greetings I am so glad I found your weblog, I really found you
    by mistake, while I was searching on Google for something else, Anyways I am here now and would just like to say
    cheers for a fantastic post and a all round entertaining blog (I
    also love the theme/design), I don’t have time to read it all at the minute but I have bookmarked it and also added your RSS feeds, so when I have time I will be back to read much more, Please do keep up the great work.

  34. Many of the chicken delicacies are also possible to be made by mixing some spices
    with other daily use items such as coconut, loaf,
    onion, garlic, mushroom, etc. Take the low-carb tortilla or
    wrap and put about a tablespoon or two of cream on it.
    If you desire a longer and better quality of life choosing include HEALTHY EATING HABITS into your lifestyle is
    a smart choice.

  35. My brother recommended I may like this blog. He used to be totally right.
    This submit actually made my day. You cann't consider simply how so much time I had spent for this info! Thanks!

  36. Hello, Neat post. There's an issue together with your web site in internet explorer, could test this? IE nonetheless is the marketplace chief and a big part of other people will leave out your magnificent writing due to this problem.

  37. What's up to every one, for the reason that I am in fact keen of reading this blog's post to be updated regularly.

    It includes nice material.

  38. Pretty nice post. I just stumbled upon your blog and wanted to say that I have truly loved browsing your
    weblog posts. In any case I'll be subscribing in your feed and I hope you write again very soon!

  39. Wonderful beat ! I wish to apprentice whilst you amend your web site, how could
    i subscribe for a blog website? The account aided me a appropriate deal.
    I had been tiny bit familiar of this your broadcast offered vibrant transparent
    idea

  40. Hmm it seems like your website ate my first comment (it was extremely long) so I guess I'll just sum it up what I had written and say, I'm thoroughly enjoying your blog.
    I too am an aspiring blog blogger but I'm still new to everything. Do you have any tips for first-time blog writers? I'd really appreciate it.

  41. Hi there! I could have sworn I've been to this blog before but after browsing through a few of the posts I realized it's new to me.
    Regardless, I'm certainly delighted I found it and I'll be book-marking it
    and checking back often!

  42. What a information of un-ambiguity and preserveness
    of valuable knowledge regarding unexpected feelings.

  43. Nice post. I learn something new and challenging on blogs I stumbleupon every day.
    It will always be useful to read through articles from other writers and use something from other websites.

  44. Usually I do not learn post on blogs, however I wish to say that
    this write-up very pressured me to take a look at and do
    it! Your writing taste has been amazed me. Thanks, quite nice post.

  45. I'm curious to find out what blog system you are working with? I'm having some minor security issues with my latest site and I'd like to find something more safeguarded. Do you have any suggestions?

  46. Layer 3 analysis takes place just once with label inspection then kicking in to
    drive forwarding. Be aware that the network you are connecting into may have certain policies for VPN connections.
    One of the many advantages of using private VPNs is that they work
    on existing ports that are difficult to block.

  47. Please let me know if you're looking for a article writer for your blog. You have some really good posts and I believe I would be a good asset. If you ever want to take some of the load off, I'd absolutely love to write some content
    for your blog in exchange for a link back to mine. Please blast me
    an email if interested. Kudos!

  48. I lose weight with my elliptical, strolling the pet and ingesting nicely. Have you been overestimating your calorie burnEating way too much or way too small will stall Pai You Guo http://www.paiyouweightloss.com/pai-you-guo-capsule-p-11.html at the same time.

コメントを残す

Jump to the top