Ruby,Perl,Pythonのメモ〜ディレクトリ読み込み〜

メモ:
・日本語の取り扱いのめも その2(ファイル名について)
・バージョンはruby 1.9.1p129,perl v5.10.0,Python 3.0.1

ruby perl python
文字コード localeのまま取得? 内部で変換 locale→Unicode文字列に自動変換?



ソースコードutf-8、コンソール:utf-8

Ruby

#!/usr/local/bin/ruby
# coding: utf-8

require 'pathname'

Pathname("./test_dir/").children(false).sort.each{|path|
  puts path
  #puts path.to_s.encoding
}

Perl

#!/usr/bin/perl
use strict;
use warnings;
use utf8;
use feature ":5.10";
use Encode;

binmode(STDOUT, ':utf8' );

# ファイル名取得
opendir my $dh, './test_dir/' or return;
my @files = sort grep !/^\.+$/, readdir($dh);
closedir $dh;

my @files_utf = map { Encode::decode('utf8',$_) } @files;
foreach my $fname(@files_utf){
  say $fname;
  #say utf8::is_utf8($fname)
}

Python

#!/usr/local/bin/python3.0
# -*- coding: utf-8 -*-

import os
fnames = os.listdir("./test_dir/")
fnames.sort()
for fname in fnames:
  print(fname)

ファイル名一覧

$ ls -a ./test_dir/
.  ..  .dot_file  .日本語ファイル  noJpFile  日本語ファイル

結果

.dot_file
.日本語ファイル
noJpFile
日本語ファイル