モジュール「Term::ReadKey
」を使うと出来る。これはUnix系OSだけじゃなくてWindows(ActivePerl 5.10.1 build 1007で確認)でも動く。
Term::ReadKey – search.cpan.org
例1:文字列を入力して貰う
1 2 3 4 5 6 | #!/usr/bin/perl use Term::ReadKey; print "type some keys : " ; ReadMode "normal" ; chomp ( my $line = ReadLine 0 ); print "you typed '$line'\n" ; |
chomp
しないと最後に改行が付いたままになってしまうので注意。
例2:画面に文字を表示しないで入力
1 2 3 4 5 6 7 | #!/usr/bin/perl use Term::ReadKey; print "enter your password : " ; ReadMode "noecho" ; chomp ( my $line = ReadLine 0 ); ReadMode "restore" ; print "\nyou typed '$line'\n" ; |
パスワード入力に使えるだろう。
例3:1文字だけ受け付ける(選択肢を選んで貰う)
1 2 3 4 5 6 7 | #!/usr/bin/perl use Term::ReadKey; print "are you Hungry? (y/n)\n" ; ReadMode "cbreak" ; my $char = ReadKey 0; ReadMode "restore" ; print "you typed '$char'\n" ; |
このスクリプトはWindowsにおいて挙動がおかしい。なぜかエンターキーだけを認識しないのだ(他のキーは全く問題ない)。そのときはTerm::Getch
を使おう。
Term::Getch – ReadKeyライクなインターフェースのMSWin32用の代替
http://okilab.jp/document/japanate/perldoc/html/Term-Getch-0.20/Term/Getch.htm
1 2 3 4 5 6 | #!/usr/bin/perl use Term::Getch; print "are you Hungry? (y/n)\n" ; my $char ; 1 while ! ( $char = getch ); print "you typed '$char'\n" ; |
例4:文字入力をn秒待つ
1 2 3 4 5 6 7 | #!/usr/bin/perl use Term::ReadKey; print "please press key within 3 seconds.\n" ; ReadMode "cbreak" ; my $char = ReadKey 3; ReadMode "restore" ; print "you typed '$char'\n" ; |
ReadKey
関数に正の数字を渡すとその秒数だけ待つ。この例だけはWindowsでうまく動かせなかった。