Re: [問題] 讓命令引數支援 -R 和 *

看板Perl作者 (Mr.3181388)時間15年前 (2010/08/22 01:31), 編輯推噓0(000)
留言0則, 0人參與, 最新討論串3/4 (看更多)
弄了一個晚上終於寫出有點像的東西了 QQ" 感謝 想請教一下我現在是想把所有檔案的各行行尾空白去除. 想法是一次讀檔,讀檔之後處理各行,處理完成後一次寫入暫存檔。 暫存檔再覆蓋原來的檔案,但是會不會因I/O太多造成太慢? 不知道有比較快的辦法嗎?-> 我之後有可能會套用在類似 Linux kernel 那樣的大目錄裡 我寫出來看起來也蠻龐大,有興趣的前輩可以順便幫忙指點一下嗎?謝謝 #!/usr/bin/perl # Usage: [-R][*][file name] use warnings ; use strict ; use 5.010 ; use File::Copy ; use File::Find ; use Cwd; my @files; file_list(\@ARGV); foreach(@files){ right_trim($_, 1); } printf "Done, %d files\n", scalar @files; unlink("tmp"); exit; #-------------------------------- # get file list from @ARGV #-------------------------------- sub file_list{ my $arg = shift; while(@$arg){ #file test & file name print $_ = shift @$arg; if(/\*/){ # all @files = glob("*.cpp *.c *.h *.txt *.pl") } elsif(/-[rR]/){ # recursive find(\&file_found, Cwd::cwd()); } else{ # specific file name push @files, $_; } } } sub right_trim{ my $file = $_ =shift; my $show = shift; # error handling return if(/tmp/); # read all readable files # write it to a tmp file say $file if $show; open(FH, '<', $file) or die $!; open(TMP, '>', "tmp") or die $!; my @before = <FH>; my @after ; foreach (@before){ s/\s+$//; $_ .= "\n" ; push @after, $_; } print TMP @after; close FH; close TMP; copy("tmp", $file) || die "copy: $!"; } sub file_found { $_ = $File::Find::name; return unless -e && -f && -r && -w ; push @files, $_ if /\.pl$/||/\.c$/||/\.h$/||/\.txt$/; } ※ 引述《zard1989 (St. Kevin)》之銘言: : ※ 引述《a3181388 (Mr.3181388)》之銘言: : : 大家好 弱者小弟我想請教一下 : : 要怎麼讓命令引數支援 -R 和 * : : 目前已經可以讓許多檔案當作引數 : : 如 try.pl 1.txt 2.txt : : 想讓程式支援資料夾下所有子資料下遞迴的所有檔案 : : 不知該怎麼做 謝謝 : 可以使用File::Find模組(http://perldoc.perl.org/File/Find.html)。 : 至於 * 的部份,你的shell(e.g. bash)會幫你展開成該目錄底下的所有檔案名稱。 : Example: : #!/usr/bin/env perl : use 5.010; : use strict; : use File::Find; : my @files; : sub wanted { : # 在這個function過濾和處理你要的檔案 : # -f 等同於 -f $_ ,測試該檔名是否為一個檔案,而非目錄或其他東西 : -f && push @files, $_; : } : # find預設會遞迴搜尋資料夾下的檔案 (preorder traversal) : find(\&wanted, @ARGV); : # 印出@ARGV中所有檔案、目錄底下的檔案的檔名 : say join " ", @files; ※ 引述《zard1989 (St. Kevin)》之銘言: : ※ 引述《a3181388 (Mr.3181388)》之銘言: : : 大家好 弱者小弟我想請教一下 : : 要怎麼讓命令引數支援 -R 和 * : : 目前已經可以讓許多檔案當作引數 : : 如 try.pl 1.txt 2.txt : : 想讓程式支援資料夾下所有子資料下遞迴的所有檔案 : : 不知該怎麼做 謝謝 : 可以使用File::Find模組(http://perldoc.perl.org/File/Find.html)。 : 至於 * 的部份,你的shell(e.g. bash)會幫你展開成該目錄底下的所有檔案名稱。 : Example: : #!/usr/bin/env perl : use 5.010; : use strict; : use File::Find; : my @files; : sub wanted { : # 在這個function過濾和處理你要的檔案 : # -f 等同於 -f $_ ,測試該檔名是否為一個檔案,而非目錄或其他東西 : -f && push @files, $_; : } : # find預設會遞迴搜尋資料夾下的檔案 (preorder traversal) : find(\&wanted, @ARGV); : # 印出@ARGV中所有檔案、目錄底下的檔案的檔名 : say join " ", @files; -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 61.229.226.68
文章代碼(AID): #1CS0ruvR (Perl)
文章代碼(AID): #1CS0ruvR (Perl)