Perl, screen the question



  • There's a job to fix a file where there's some kind of "," "," and "? We need to remove the gap before the sign and the double gaps. Write this method:

    sub someFunc
    {
        my @s_trash_arr = 
        (
            [ "  ", " " ],
            [ " ,", " " ],
            [ " \.", "\." ],
            #[ " \?", "\?" ],
            [ " !", "!" ]
        );
    
    my $s_res = shift();
    
    for( my $i = 0; $i < @s_trash_arr; $i++ )
    {
        my $s_substring = $s_trash_arr[ $i ][ 0 ];
        my $s_replacement = $s_trash_arr[ $i ][ 1 ];
    
        while( index( $s_res, $s_substring ) != -1 )
        {
            $s_res =~ s/$s_substring/$s_replacement/;
        }
    }
    
    return $s_res;
    

    }

    Trouble in "?

    Decided in solitary confinement:

    [ ' ?', '?' ],

    Although everything now works regularly:

    $s_res=~s/ +([ ,.?!])/$1/g;



  • Double gap management and symbol gaps ,.?! may be performed by the following operation

    $source =~ s/ +([ ,\.?!])/$1/g;
    

    In terms of search, a gap is found (first) \sfollowed by one of the symbols in the set [\s,\.?!]♪ Specified in parentheses () later submitted in local replacement $1 (in the case of a more complex substation, for example, $100the operation will not be carried out, as the search for an expression with number 100 will be carried out in order to subtract with number 1 and add two zeros to it to the right. ${1}00) Thus, all the words found will be inserted except for the initial gap. Parameter g He's redefining until there's nothing to replace.

    Note: This code removes not only two gaps, but also any sequence from more than one gap, including before the intake symbols (only cleaning one gap).

    As for your code, re-detection surgery. while could be implemented with a parameter g search.




Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2