Kerby82
Kerby82

Reputation: 5146

perl blank substitution in a string

I have this two kind of strings:

EVASA           2144
IN ELABORAZIONE         16278

I need some perl script to substitute all the blanks with just one.

The output I need is:

EVASA 2144

Any suggestion?

Upvotes: 0

Views: 3503

Answers (4)

Peer Stritzinger
Peer Stritzinger

Reputation: 8372

You can also use the troperator with the s Option, this can do more things for you (transforming characters), probably faster than the regexp approach

$a =~ tr/ \t/ /s;

Explanation can be found in the perlop manpage:

perldoc perlop

Upvotes: 0

Dave Cross
Dave Cross

Reputation: 69244

My suggestion would be that you spend some time reading the Regular Expression tutorial that is distributed with every modern version of Perl.

Upvotes: 4

nonopolarity
nonopolarity

Reputation: 150976

$a = "hello    \t world";
$a =~ s/\s+/ /;
print $a;

if you may have multiple places in the string where you want the substitution to take place, use

$a = "hello    \t world    hi";
$a =~ s/\s+/ /g;
print $a;

Upvotes: 2

Dave Vogt
Dave Vogt

Reputation: 19492

You can use a very simple regex:

#!/usr/bin/perl
use strict;

my $line = 'EVASA           2144';

# This is the line that actually does the work
$line =~ s/\s+/ /g;

print $line, "\n";

Upvotes: 7

Related Questions