Search code examples
perlfilenewlineblank-line

Delete the first line using Tie::File without leave a newline at the end of the file


I use the following code to delete the first line of a file:

use Tie::File;
tie @task_queue, 'Tie::File', $queue_path or die $!;
shift @task_queue;
$#task_queue -= 1;
untie @task_queue;

The file content is like:

line1
line2
line3

But when I use the code, it will delete the line1 but leave a newline at the end of the file like this:

line2
line3
# <- here is a blank line

Since I use this file as a queue, if I add some new line after, it will become:

line2
line3
# <- here is a blank line
line4

So is there any way to avoid leaving a blank line when using Tie::File to delete the first line?


Solution

  • Thanks to all that help with this. I found a solution, it's not beautiful code but works. I also found that the blank line is still generated even if I do only tie and untie(no action between them). It may be some design issue of the module.

    use Tie::File;
    tie @task_queue, 'Tie::File', $queue_task_path or die $!;
    shift @task_queue;
    untie @task_queue;
    print("Removing the blank line.\n");
    my $queue_task_file_size = -s $task_queue;
    truncate($task_queue, $queue_task_file_size - 1);