How can I open a Unicode file with Perl?

后端 未结 4 1319
广开言路
广开言路 2021-01-04 17:58

I\'m using osql to run several sql scripts against a database and then I need to look at the results file to check if any errors occurred. The problem is that Perl doesn\'t

4条回答
  •  一整个雨季
    2021-01-04 18:36

        #
        # -----------------------------------------------------------------------------
        # Reads a file returns a sting , if second param is utf8 returns utf8 string
        # usage:
        # ( $ret , $msg , $str_file )
        #         = $objFileHandler->doReadFileReturnString ( $file , 'utf8' ) ;
        # or
        # ( $ret , $msg , $str_file )
        #         = $objFileHandler->doReadFileReturnString ( $file ) ;
        # -----------------------------------------------------------------------------
        sub doReadFileReturnString {
    
            my $self      = shift;
            my $file      = shift;
            my $mode      = shift ;
    
            my $msg        = {} ;
            my $ret        = 1 ;
            my $s          = q{} ;
    
            $msg = " the file : $file does not exist !!!" ;
            cluck ( $msg ) unless -e $file ;
    
            $msg = " the file : $file is not actually a file !!!" ;
            cluck ( $msg ) unless -f $file ;
    
            $msg = " the file : $file is not readable !!!" ;
            cluck ( $msg ) unless -r $file ;
    
            $msg .= "can not read the file $file !!!";
    
            return ( $ret , "$msg ::: $! !!!" , undef )
                unless ((-e $file) && (-f $file) && (-r $file));
    
            $msg = '' ;
    
            $s = eval {
                 my $string = ();    #slurp the file
                 {
                    local $/ = undef;
    
                    if ( defined ( $mode ) && $mode eq 'utf8' ) {
                        open FILE, "<:utf8", "$file "
                          or cluck("failed to open \$file $file : $!");
                        $string =  ;
                        die "did not find utf8 string in file: $file"
                            unless utf8::valid ( $string ) ;
                    }
                    else {
                        open FILE, "$file "
                          or cluck "failed to open \$file $file : $!" ;
                        $string =  ;
                    }
                    close FILE;
    
                 }
                $string ;
             };
    
             if ( $@ ) {
                $msg = $! . " " . $@ ;
                $ret = 1 ;
                $s = undef ;
             } else {
                $ret = 0 ; $msg = "ok for read file: $file" ;
             }
             return ( $ret , $msg , $s ) ;
        }
        #eof sub doReadFileReturnString
    

提交回复
热议问题