Split line with perl

前端 未结 5 651
深忆病人
深忆病人 2021-01-23 03:57
   title: Football team: Real Madrid stadium: Santiago Bernabeu players: Zinédine Zidane, Ronaldo, Luís Figo, Roberto Carlos, Raúl personnel: José Mourinho (head coach)          


        
5条回答
  •  余生分开走
    2021-01-23 04:32

    This should do it. line.txt contains "title: Football team: Real Madrid stadium: Santiago Bernabeu players: Zinédine Zidane, Ronaldo, Luís Figo, Roberto Carlos, Raúl personnel: José Mourinho (head coach) Aitor Karanka (assistant coach (es))"

    #!/usr/bin/perl
    use strict;
    use warnings;
    
    my $fn="./line.txt";
    
    open(IN,$fn);
    my @lines=;
    
    my %hash;
    my $hashKey;
    
    foreach my $line (@lines){
            $line=~s/\n//g;
            my @split1=split(" +",$line);
            foreach my $split (@split1){
                    if($split=~m/:$/){
                            $hashKey=$split;
                    }else{
                            if(defined($hash{$hashKey})){
                                    $hash{$hashKey}=$hash{$hashKey}.$split." ";
                            }else{
                                    $hash{$hashKey}=$split." ";
                            }
                    }
            }
    }
    
    close(IN);
    
    
    foreach my $key (keys %hash){
            print $key.":".$hash{$key}."\n";
    }
    

提交回复
热议问题