2011-03-29 144 views
1

我必須讀取a file中的行並將它們存儲到Perl中的哈希中。許多這些行在開始時都有特殊的字符序列,我需要在存儲之前將其刪除。這些字符序列是如何從Perl中的字符串開頭刪除字符序列列表?

| || ### ## @@||

例如,如果是||https://ads,我需要得到https://ads;如果###http,我需要得到http

我需要排除這些字符序列。我想通過將所有字符序列排除在數組中,然後檢查該行是否以這些字符序列開頭並刪除這些字符序列來完成此操作。什麼是這樣做的好方法?

據我已經爲:

our $ad_file = "C:/test/list.txt"; 
our %ads_list_hash =(); 

my $lines = 0; 

# List of lines to ignore 
my @strip_characters = qw /| || ### ## @@||/; 

# Create a list of substrings in the easylist.txt file 
open my $ADS, '<', $ad_file or die "can't open $ad_file"; 

while(<$ADS>) { 
    chomp; 
    $ads_list_hash{$lines} = $_; 
    $lines ++; 
} 

close $ADS; 

我需要添加到每個行的開頭刪除@strip_characters如果其中任何存在的邏輯。

+1

把所有的字符表達代替,然後用它來代替(刪除)不想要的字符 – 2011-03-29 08:52:29

回答

3

你爲什麼不用正則表達式來做呢?像

$line =~ s/^[#@ |]+//; 

應該工作。

4

可能有點過於複雜,一般的任務,但仍..

my $strip = join "|", map {quotemeta} @strip_characters; 
# avoid bare [] etc. in the RE 

# ... later, in the while() 
    s/^(?:$strip)+//o; 
    # /o means "compile $strip into the regex once and for all" 
1

如果你想刪除的字符列表(根據你的標題),然後一個非常簡單的正則表達式將工作。
在循環中,添加下面的正則表達式

while(<$ADS>) { 
    chomp; 
    s/^[#@ \|]+//; 
    $ads_list_hash{$lines++} = $_; 
} 

注意管道charachter( '|')被escapted。 但是,看起來您要刪除表達式的列表。您可以執行以下操作:

while(<$ADS>) { 
    chomp; 
    s/^((\|)|(\|\|)|(###)|(##)|(@@\|\|))+//; 
    $add_list_hash{$lines++} = $_; 
} 

您說表達式列表存儲在數組或單詞中。在你的示例代碼中,你用'qw'創建這個數組。如果在編譯時不知道表達式列表,則可以在變量中構建正則表達式,然後使用它。

my @strip_expression = ... // get an array of strip expressions 
my $re = '^((' . join(')|(',@strip_expression) . '))+'; 

,然後,使用下面的語句在循環: S/$重新//;

最後,與問題無關的一件事可以說是關於代碼:使用Array而不是Hash來將整數映射到一組字符串會更合適。除非你有其他要求,最好有:

our @ads_list; // no need to initialize the array (or the hash) with empty list 
... 
while(<$ADS>) { 
    chomp; 
    s/.../; 
    push @ads_list, $_; 
} 
+1

注意管道charachter(原文如此)(「|」)並不需要被escapted(原文如此)裏面的時候一個角色類。 – tadmc 2011-03-29 13:56:27

1
$ads_list_hash{$lines} = $_; 
$lines ++; 

不要那樣做。如果你想要一個數組,使用數組:

push @ads_lines, $_; 

的編程#7肖恩的規則:當創建數據結構:如果保留順序很重要,使用數組;否則使用散列。

+0

我喜歡你的好規矩! – 2011-03-31 01:01:48

0

因爲替換會返回他們是否執行了任何操作,所以您可以使用 替換字符串來搜索您的模式,如果它存在,請將其刪除。

while(<$ADS>) { 
    next unless s/^\s*(?:[#]{2,3}|(?:@@)?[|]{1,2})\s*//; 
    chomp; 
    $ads_list_hash{$lines} = $_; 
    $lines ++; 
}