globé¢æ° - ãã£ã¬ã¯ããªã«å«ã¾ãããã¡ã¤ã«ä¸è¦§ãåå¾
globé¢æ°ã使ç¨ããã¨ããã¡ã¤ã«ä¸è¦§ãåå¾ãããã¨ãã§ãã¾ãã
my @all_files = glob "*";
ãã¡ã¤ã«ä¸è¦§ãåå¾ããã«ã¯ãglob æ¼ç®åã使ãã¾ãã対象ã¯ãã«ã¬ã³ããã£ã¬ã¯ããªã®ãã¡ã¤ã«(ãã£ã¬ã¯ããªãå«ã)ã«ãªãã¾ããå¥ã®ãã£ã¬ã¯ããªã®ãã¡ã¤ã«ä¸è¦§ãåå¾ããã¨ãã¯chdir関数 ã§ãã«ã¬ã³ããã£ã¬ã¯ããªã移åããããç¸å¯¾ãã¹ãããã¯ã絶対ãã¹ã§ã表ç¾ãã¾ãã
glob ã®å¼æ°ã®è¡¨ç¾ä¾
"*" | .ã§å§ã¾ããªãããã¹ã¦ã®ãã¡ã¤ã« |
"*.txt" | .txt ã§çµãããã¡ã¤ã« |
"*.txt *.pl | .txt ãããã¯ã .pl ã§çµãããã¡ã¤ã«( .txt 㨠.pl ã®éã«ç©ºç½ãããã¾ã ) |
"* .*" | ãã¹ã¦ã®ãã¡ã¤ã«( * 㨠.* ã®éã«ç©ºç½ãããã¾ã ) |
"lib/* | libãã£ã¬ã¯ããªä»¥ä¸ã®ãã¡ã¤ã« |
c:/dir/* | 絶対ãã¹ã§æå® |
空ç½ã§ãåºåãã¨è¤æ°ã®ãã¿ã¼ã³ãæå®ã§ãã¾ããç¸å¯¾ãã¹ä»¥å¤ã«ãã絶対ãã¹ã使ããã¨ãã§ãã¾ãã* ã¯Unixã®ã·ã§ã«ã§ç¨ããããã¯ã¤ã«ãã«ã¼ãã®ã²ã¨ã¤ã§ããglobé¢æ°ã¯ãã·ã§ã«ã®ã¯ã¤ã«ãã«ã¼ãå±éã®è¦åã«ãããã£ã¦ã*ãå«ããã¡ã¤ã«åãå±éãã¾ãã
ãµã³ãã«
globé¢æ°ã®ãµã³ãã«ã§ãã
use strict; use warnings; # ã«ã¬ã³ããã£ã¬ã¯ããªã®ãã¡ã¤ã«ä¸è¦§ãåå¾ããã # glob print "1: ã«ã¬ã³ããã£ã¬ã¯ããªã®ãã¡ã¤ã«ä¸è¦§ãåå¾ããã\n"; # * ã¯ã. ã§å§ã¾ããªããã¹ã¦ã®ãã¡ã¤ã«ãè¡¨ç¾ my @all_files = glob "*"; print join("\n", @all_files) . "\n\n"; print "2: .txt ã§çµãããã¡ã¤ã«ä¸è¦§ãåå¾ããã\n" ; my @text_files = glob "*.txt"; print join("\n", @text_files) . "\n\n"; print "3: .txt 㨠.pl ã§çµãããã¡ã¤ã«ä¸è¦§ãåå¾ããã\n"; # è¤æ°ãã¿ã¼ã³ããå ´åã¯ç©ºç½ã§åºåã my @text_and_pl_files = glob "*.txt *.pl"; print join("\n", @text_and_pl_files) . "\n\n"; print "4: é常ãã¡ã¤ã«ã®ä¸è¦§ãåå¾ããã\n"; my @normal_files = glob "*"; # è¤éãªãã¨ããããã¨ãã¯,"*" 㧠# ãã¹ã¦ã®ãã¡ã¤ã«ãåå¾ãã¦ããã # grep ã§é¸å¥ããã @normal_files = grep{ -f $_ } @normal_files; print join("\n", @normal_files) . "\n\n";
åè:join関数
å®è¡çµæ
1: ã«ã¬ã³ããã£ã¬ã¯ããªã®ãã¡ã¤ã«ä¸è¦§ãåå¾ããã a.exe a.pl aaa DBIx-Custom dir_20080530_4944 hello.exe hello.pl lib yuki-kimoto-Portablebbs-b578c1d yuki-kimoto-Portablebbs-b578c1d.zip 2: .txt ã§çµãããã¡ã¤ã«ä¸è¦§ãåå¾ããã 3: .txt 㨠.pl ã§çµãããã¡ã¤ã«ä¸è¦§ãåå¾ããã a.pl hello.pl 4: é常ãã¡ã¤ã«ã®ä¸è¦§ãåå¾ããã a.exe a.pl hello.exe hello.pl yuki-kimoto-Portablebbs-b578c1d.zip
Windowsã§ã¯globé¢æ°ã¯æ£ããåä½ããªãã®ã§ãã£ã¬ã¯ããªãã³ãã«ã使ã
ãã¡ã¤ã«ä¸è¦§ãåå¾ããã¨ãã«globé¢æ°ã使ããã¨ãå¤ãã¨æãã¾ããããã©ãä»ã®ã¨ããã¯globé¢æ°ã¯Windowsã§ã¯æ£ããåããªãã¨è¦ã¦ãããã»ããããã§ãããããã£ã¬ã¯ããªåã«ç¹å®ã®æååãå«ãå ´åã¯ããã¡ã¤ã«ä¸è¦§ãæ£ããåå¾ãããã¨ãã§ãã¾ããã
ã§ãã®ã§ãglobé¢æ°ã使ã代ããã«ã以ä¸ã®ãããªãã¡ã¤ã«åã®ä¸è¦§ãåå¾ããé¢æ°ãä½ãã®ãããã§ãããããã£ã¬ã¯ããªãã³ãã«ããªã¼ãã³ããã«ã¯opendir関数ããã£ã¬ã¯ããªã®èªåºãã«ã¯readdir関数ã使ç¨ãã¾ãã
sub get_files { my $dir = shift; opendir my $dh, $dir or die qq/Can't open directory "$dir": $!/; my @dirs = map { "$dir/$_" } grep { $_ ne '.' && $_ ne '..' } readdir $dh; return @dirs; }
ã使ãæ¹
my @files = get_files('c:/pictures');