Perlコマンド – 覚え書き

よく使うPerlコマンドのメモ帳代わり
【ファイル名解析】- File::Basename –
use File::Basename;
our @osType = ('Unix','VMS','MacOS','AmigaOS','MSDOS','MSWin32','DOS','Epoc','OS2','RISCOS');
fileparse_set_fstype($osType[0]); ## - Set FileSystem -> Unix ← デフォルトがUnixなので省略可能
our @extList = ('.jpg','.png'); ## - 拡張子を分けたい場合にはこの定義が必須
    – 使用例 –
    定義
    my $filepath = "/home/sample/file/file_sample_01.jpg";
    
  1. ファイル名取得:basename
  2. my $bn = basename($filepath);   $bn -> file_sample_01.jpg my $bn = basename($filepath,@extList);   $bn -> file_sample_01 (※:拡張子の定義を引数で渡すと、拡張子は省かれる)
  3. ディレクトリ取得:dirname
  4. my $dir = dirname($filepath);   $dir -> /home/sample/file/
  5. ファイル名解析:fileparse
  6. my ($name,$path,$ext) = fileparse($filepath);   $name -> file_sample_01.jpg   $path -> /home/sample/file/   $ext -> my ($name,$path,$ext) = fileparse($filepath,@extList);   $name -> file_sample_01   $path -> /home/sample/file/   $ext -> .jpg

【ファイルのタイムスタンプ取得】- stat –
my $filename = "sample.txt";
my @filestat = stat $filename;

my ($sec, $min, $hour, $mday, $mon, $year) = localtime($filestat[9]);

## - [8]:アクセス日 / [9]:更新日

【ファイルのタイムスタンプ変更】- utime –
my @filelist = ('sample.txt');
my $atime = time();
my $mtime = time();

utime $atime, $mtime, @filelist;

## - $atime:アクセス日 / $mtime:更新日

【文字列を任意の区切り箇所でソート】- sort with cmp –
my @list = ('sampleList.txt');
my $sp = ",";
my $n = 3; ## ←ソートしたい箇所

my @result = sort { (split(/$sp/,$a))[$n] cmp (split(/$sp/,$b))[$n] } @list;

## - $sp:区切り文字 / $n:ソート箇所