replace multiple spaces between words with single space.

Discussion in 'Perl Misc' started by Shashank Khanvilkar, Mar 14, 2005.

  1. Hi,
    Suppose I have a variable defined as:

    $a = "This is a good example";

    Note that there are multiple blanks between the words.
    If i want to convert the above string to
    $b = "This is a good example"

    Is there any shortcut to do the above.
    I know the long way as

    @a_T = split(/\s/, $a);
    foreac $i (@a_T){
    if ($i){
    $b = $b.$i." ";
    }
    }

    I want to use substitute but canot seem to get it right..
    Thanks for any help
    Shashank
     
    Shashank Khanvilkar, Mar 14, 2005
    #1
    1. Advertisements

  2. :$a = "This is a good example";

    :Note that there are multiple blanks between the words.
    :If i want to convert the above string to
    :$b = "This is a good example"

    :Is there any shortcut to do the above.

    ($b = $a) =~ s/ +/ /g;

    Or if you want to generalize this a bit,

    ($b = $a) =~ s/\s+/ /g;

    \s matches whitespace (includes tabs and various non-ASCII whitespace.)
    The + modifier means "one or more of the previous group".
    The trailing g means "global replace" -- that is, do for all occurances
    in the input string.

    The other trick is the ($b = $a). If you were to use

    $b = $a =~ s/\s+/ /g;

    then $b would be assigned the result of the =~ operation; in a scalar
    context, =~ with a substitution returns the number of substitutions made,
    so $b would end up as a count instead of as the new string. The
    ($b = $a) part causes the assignment to be done first, and then the =~
    acts upon the string so created.
     
    Walter Roberson, Mar 14, 2005
    #2
    1. Advertisements

  3. Let's suppose.
    It is probably not a good idea to use $a and $b. See perldoc -f sort.
    use strict;
    use warnings;
    Please post real code.

    syntax error at v.pl line 2, near "){"
    Execution of v.pl aborted due to compilation errors.

    Have you read the relevant section in perldoc perlop?

    use strict;
    use warnings;

    my $src = q{This is a good example};

    my $dest;

    $dest = join ' ', split /\s+/, $src;
    print "$dest\n";

    ($dest = $src) =~ s/\s+/ /g;
    print "$dest\n";

    Sinan
     
    A. Sinan Unur, Mar 14, 2005
    #3
  4. ( $b = $a ) =~ y/ //s;


    John
     
    John W. Krahn, Mar 14, 2005
    #4
  5. Shashank Khanvilkar

    Anno Siegel Guest

    tr/// does that a bit faster:

    ($b = $a) =~ tr/ //s;

    Anno
     
    Anno Siegel, Mar 15, 2005
    #5
    1. Advertisements

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments (here). After that, you can post your question and our members will help you out.