The reason you are getting
Subjects :*****Computer
instead of
Subjects :*****
Is that you split the original string on linebreaks R+
and then edit the lines, after which you join the string back together. Since Computer
is on a new line, it does not get edited.
my @tmp1 = split(/R+/,$fm_log[$i]); # <---- splitting the line
foreach (@tmp1) { # editing the pieces
$_ =~ s!^s+!xxxx! if $_ !~ m!:!;
$_ =~ s!(Times+:)s+.*!${1}xxx!;
$_ =~ s!(Subjectss+:)s+.*!${1}xxx!;
}
$fm_log[$i] = join("
",@tmp1); # joining the pieces
In other words, if you have a string such as:
my $str = "foo: bar
baz";
Then split the string on newline and try to remove everything after foo:
my @pieces = split /R+/, $str;
Now @pieces
will contain this:
$VAR1 = [
'foo: bar',
'baz'
];
And if we try to edit them with s/foo:.*//
, we will never affect the baz
part of the original string.
Since you have a file that contains fields separated by lines that start with word(s) followed by a colon, followed by content that may contain newlines, what you need is to first separate the fields from each other.
Your fields look something like...
TITLE : CONTENT
CONTENT ...
TITLE : CONTENT ...
There may be modules that read this format that are more suitable. I made up this quick hack to coerce the data into a hash, where you can edit the fields by simply assigning new values to them.
use strict;
use warnings;
use Data::Dumper;
my $fm_log= " Name : Piyush Prasad
Class : 12th
Stream : Science
Subjects : Physics Chemistry Maths
Computer
Text : what ever happens to this code does not
even matter to me
Time : 10.304534
";
my @info = split /^ *([w ]+) : /m, $fm_log; # split into fields
s/s+/ /g for @info; # cleanup start
s/^s+|s+$// for @info;
shift @info; # cleanup complete
my %info = @info;
print Dumper \%info; # show the data structure we made
$info{Subjects} = "****";
$info{Time} = "****";
printf("%s : %s
", $_, $info{$_}) for qw(Name Class Stream Subjects Text Time);
This will output
$VAR1 = {
'Class' => '12th',
'Stream' => 'Science',
'Time' => '10.304534',
'Subjects' => 'Physics Chemistry Maths Computer',
'Text' => 'what ever happens to this code does not even matter to me',
'Name' => 'Piyush Prasad'
};
Name : Piyush Prasad
Class : 12th
Stream : Science
Subjects : ****
Text : what ever happens to this code does not even matter to me
Time : ****