首頁  >  文章  >  系統教程  >  如何在Windows控制台上利用Perl處理UTF8

如何在Windows控制台上利用Perl處理UTF8

王林
王林轉載
2024-01-12 09:42:05962瀏覽

如何在Windows控制台上利用Perl處理UTF8

如何在Windows控制台上利用Perl處理UTF8

制定控制台使用UTF8,顯示出來的字體也很難看,當Perl程式和Perl要讀取的檔案都使用UTF8編碼時,該怎麼辦呢?先看如下程式:

#!/usr/bin/perl

use encoding 'utf8', STDIN=>'gb2312', STDOUT=>'gb2312';

open(FILE,"c:\\test1.txt");

binmode(FILE,":encoding(utf8)");

@lines=;

close(FILE);

for($i=0; $i

print $lines[$i];

print "\n";

}

$str="你好";

print $str;

該程式用Perl去讀取一個文字檔test1.txt,然後顯示到控制台上。關鍵在於:

1. use encoding 'utf8', STDIN=>'gb2312', STDOUT=>'gb2312';

use encoding 'utf8' : 指定該腳本檔案的編碼格式為​​utf8;

STDIN=>'gb2312', STDOUT=>'gb2312': 輸入與輸出採用GB2312字元集。

這樣,Perl腳本中的漢字即可被輸出。

2:binmode(FILE,":encoding(utf8)");

指定開啟的檔案FILE的編碼格式為​​utf8,這樣就能正確的讀入資料到@lines中了。

這樣就實作了Perl在Windows控制台上處理UTF8字元了。

Perl如何讀取文字的最後一行非空字串

三個方法如下:

#!/bin/perl -w

use strict;

my $str = "abcsfsaf#sdagasdga#sdgaghoiiopjh#dsfjkopa hkl;fjh#dsjfklpafj";

## 方法一

my $pos = -1;

my $num = 0;

while (($pos = index($str, "#", $pos)) >-1) {

print "found at $pos\n";

$pos ;

$num ;

}

print "找到$num個!\n";

# 方法二

my $count = 0;

while( $str =~ /#/g )

{

$count ;

}

print $count,"\n";

## 方法3

my $cc = 0;

my $tmp = 0;

if( $tmp = () = ($str =~ /#/g ) )

{

$cc = $tmp;

###}### ###print "$cc\n";### ###用Perl語言:寫一個程式讀入一串單字一個單字一行輸出每一 ### ####/usr/bin/perl### ###open (IN, 'D:\\words.txt ') || die $!;### ###@words=();### ###close IN;### ###open (OUT,'>','D:\\wordlist.txt')or die $!;### ###foreach $line(@words){### ###$line=~s/\n//g;### ###@words=split /\s /,$line;### ###foreach $word(@words){### ###$word=~s/\W //;### ###$freq {$word} ;### ###print OUT $word ."=>". $freq{$word}."\n";### ###}### ###}### ###close OUT;### ###你試試看這個程序,檔案可以不用每行一個單詞,直接讀取原始文字就好!有問題再交流! ### ###教一個perl程式題:從檔案中讀取內容內容就一排是一些文字 ### ####!/usr/bin/perl -w### ###use strict;### ###die "perl $0 " unless(@ARGV==1);### ###open (IN,$ARGV[0]) or die "Can't open file $ARGV[0]!\n";### ###open (OUT,">data2") or die "Can't create file data2\n";### ###while(){### ###chomp;### ###my @tmp=split /\t/,$_;### ###for(my $tmpc=1;$tmpcif($tmp[$tmpc-1] eq $tmp[$tmpc]){### ###print OUT "$tmp[$tmpc-1]\@2\t\@\@\@";### ###$tmpc ;### ###next;### ###}### ###print OUT "\t$tmp[$tmpc-1]";### ###}### ###print OUT "\n";### ###}###

以上是如何在Windows控制台上利用Perl處理UTF8的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:docexcel.net。如有侵權,請聯絡admin@php.cn刪除