How do I delete multiple lines with different values in an array.
Here is code below I have which works for 1 match in array if I define it but can't get it work with multiple values in an array. Foreach my $username (@remove_users) complains about match when I try wrapping it around foreach my $line (@file_lines). Thanks for your help.
Code:
@remove_users;
if (not defined $test_file) {
#Make sure that the $test_file was passed in too.
die qq(Name of log file not passed to subroutine "removeUsers"\n);
}
# Read file into an array for processing
open( my $read_fh, "<", $test_file )
or die qq(Can't open file "$test_file" for reading: $!\n);
my @file_lines = <$read_fh>;
close( $read_fh );
# Rewrite file with the line removed
open( my $write_fh, ">", $test_file )
or die qq(Can't open file "$test_file" for writing: $!\n);
foreach my $line ( @file_lines ) {
print {$write_fh} $line unless ( $line =~ /$user_remove/ );
}
close( $write_fh );
print( "User successfully removed.<br/>" );
one solution could be (assuming the users to remove are in @users_remove array) to replace the loop with:
Code:
LINE:
foreach my $line (@file_lines) {
foreach my $user_remove (@users_remove) {
next LINE if $line =~ /$user_remove/;
}
print {$write_fh} $line;
}
It's not the best solution: you use a regexp while you could probably just compare the line with normal eq operator (after chomping) and you always iterate over all users to remove, but it should work. A suggestion for an optimized solution could be (assuming a line consists solely of a username):
Code:
my %users_remove = map {$_=>1} @users_remove;
chomp(@file_lines);
foreach my $line (@file_lines) {
next if $users_remove{$line};
print {$write_fh} $line;
}
Thanks SixTease. I should have posted earlier error I get, which is same as you when I do a match. I would prefer to use match because username is not the only user details on same line. Here is error below which is usually in the format of domain\username (eg. BEN\HI00123) hence the \slash causing me grief because any letter can be after the \ escaping that character.
Code:
Unrecognized escape \H passed through in regex; marked by <-- HERE in m/BEN\H <-
- HERE I00123
/ at C:\Temp\ts_access_over_90_days.ipl line 644.
When I use domain\\username but still get another error below when I try
Code:
$line =~ s|\\|\\\\|;
above
Code:
next LINE if $line =~ /$user_remove/;
Here is 2nd error after trying substitution:
Code:
Unrecognized escape \H passed through in regex; marked by <-- HERE in m/BEN\\\\\
\\\\\\H <-- HERE I00123
/ at C:\Temp\ts_access_over_90_days.ipl line 646.
Bookmarks