I know there are various unicode perlrun options, but I've found I didn't need it. My .bashrc is set to use en_US.UTF-8.
I'm using Perl 14.1, and this seems to work well. If any unicode experts have a way to simplify the code, especially to avoid using decode(), please speak up.
Just run the script with a string containing a unicode character, like ./script 本 and it will recursively search and report all directories or filenames with that string in it's name, and also search thru every file regardless of name for the string in it's content.
#!/usr/bin/perl use warnings; use strict; use File::Find; use Encode qw(decode); my $path = '.'; # use utf8::all or use the commented lines beneath use utf8::all; # use this instead of the utf8::all module # make input strings utf8 #$_ = Encode::decode('UTF-8', $_) for @ARGV; # make STDIN STDOUT STDERR to be utf8, #binmode STDOUT, ':encoding(UTF-8)'; #binmode STDIN, ':encoding(UTF-8)'; #binmode STDERR, ':encoding(UTF-8)'; my $search_str = $ARGV[0] or die "need a search string\n $!\n"; print "search-> $search_str\n"; my $regex = qr/\Q$search_str\E/; print "regex-> $regex\n"; # finds all files with $regex in it's filename # and all files who have a line matching $regex find (sub { # make File::Find unicode $_ = decode('utf8',$_); $File::Find::dir = decode('utf8', $File::Find::dir); if ($_ =~ /$regex/){ # check for name match if( -d ){ print "dirname match: $File::Find::dir/$_\n" }else{ print "filename match: $File::Find::dir/$_\n" } } # now check filename's contents my $filename = $_; # avoid $_ confusion # the following line is not needed with utf8::all, # otherwise use the following #open (my $fh,'<:encoding(UTF-8)', $filename); open (my $fh,'<', $filename) or warn "Can't open $filename +$!\n"; while(<$fh>){ if ($_ =~ /$regex/){ print "text match in $File::Find::dir/$filename: $_\n"; } } }, $path);
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: UTF-8 and File::Find
by Corion (Patriarch) on Jun 30, 2012 at 16:02 UTC | |
by zentara (Cardinal) on Jun 30, 2012 at 16:13 UTC |