I am perl bginner (but i guess logic is same for all programming languages like C++ and C in my case its perl).

What i want to achieve ?

I have a text file i read that file which contains different IPaddress Time in each line and when i find a particular Time then i delete that line.

What is the problem ?

The problem is when i open a file and check for time (to see that is this the particular time i am looking for to delete this line) then it need to read that file (I mean '<' operation) but when i have to delete that particular line after finding that correct time i need to do write operation (I mean this '>' operation). Now when i try to achieve this i use this code (which will surely not work as the file is opened in read mode we cannot delete (i mean write to it)):

 open my $fhi, '<', 'C:\shekhar_Axestrack_Intern\WindowCreation\ListOfIpAdress.txt', or die "Could not open file $!";
    while (my $line = <$fhi>) 
       ## Doing some operation using $fhi in read mode
        if($Time >'33')
          $fhi->autoflush; #flush the line if time is greater than 33 hours, whereas all other lines which do not folow the condition are still present in file.
    close $fhi;

How to delete that particular line in text file (after some manupulation of time ?)

1 Answer 1


You can use Tie::File:

tie @lines,'Tie::File','C:\...';
for $line (@lines){
    # Do some operation on $line
    # Test if you need to delete the line
    push @to_delete, $i++ if $need_to_delete;
delete @lines[@to_delete]

Note that the variable @lines becomes magical: each element of the array is a line from the file and any changes you make to that element are reflected in the file. No safety net so make a backup first!!

  • too late but i already done Jan 20, 2015 at 4:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.