Sruthi Chowdavarapu Sruthi Chowdavarapu - 4 months ago 9
Perl Question

how to do match a word in a line in perl and remove it and using them separately?

for example in one perl file it is like this:

123 abc xyz
456 abc sdf
789 abc ghj


Now from above lines I need to separate remove
abc
and assign

value 1=123
value 2= xyz
value 3= 456
value 4= sdf


Help me how to code for above requirement.

Answer
#!/usr/bin/perl

use strict;
use warnings;
use 5.010;

my $count = 0;

while (<DATA>) {
  chomp;
  for (split / abc /) {
    $count++;
    say "value $count=", ($count == 1 ? '' : ' '), $_;
  }
}

__DATA__
123 abc xyz
456 abc sdf
789 abc ghj

Or, perhaps a more data-driven approach to determining which rows omit the space after the =:

#!/usr/bin/perl

use strict;
use warnings;
use 5.010;

my %nospace = (
  1 => 1,
);

my $count = 0;

while (<DATA>) {
  chomp;
  for (split / abc /) {
    $count++;
    say "value $count=", ($nospace{$count} ? '' : ' '), $_;
  }
}

__DATA__
123 abc xyz
456 abc sdf
789 abc ghj