Remove last new line

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • dh87lfc
    New Member
    • Oct 2007
    • 11

    Remove last new line

    Hi,
    I have a slight problem which is probably easy to fix, but I am still fairly new to this language. Firstly, I shall show you the code:

    [CODE=perl]
    #!/usr/bin/perl

    opendir(DIR, "directory" ) || die "Cannot open directory";
    my @file = readdir(DIR);
    closedir(DIR);
    open(NF, ">file" || die "Cannot open file");

    foreach my $file (@file)
    {
    @file = sort(@file);
    open(FH, $file) or die "$!";

    while (<FH>)
    {
    if ((/Jan-\d\d/) || (/Feb-\d\d/) || (/Mar-\d\d/) || (/Apr-\d\d/) || (/May-\d\d/) || (/Jun-\d\d/) || (/Jul-\d\d/) || (/Aug-\d\d/) || (/Sep-\d\d/) || (/Oct-\d\d/) || (/Nov-\d\d/) || (/Dec-\d\d/))
    {
    chomp;
    print NF "$_\n";
    }
    }
    }
    close(NF);
    close(FH);
    [/CODE]

    As you can see, I am printing the lines of the file with each line on a new line. However, I would like to somehow tell it not to make a new line if it is the last line in the file. I have tried removing it through the command prompt, and even tried manually removing it using a text editor, but it is always there. I am using this file to plot data, and as such there must not be a new line at the end because the values for that line will be 0. Any help would be appreciated, thanks in advance.
  • kaioshin00
    New Member
    • Nov 2006
    • 46

    #2
    Maybe

    [CODE=perl]print NF "$_\n" if length $_ > 0;[/CODE]

    ?

    Comment

    • KevinADC
      Recognized Expert Specialist
      • Jan 2007
      • 4092

      #3
      untested but should work:

      [CODE=perl]#!/usr/bin/perl

      use warnings;
      use strict;

      opendir(DIR, "directory" ) || die "Cannot open directory";
      my @file = readdir(DIR);
      closedir(DIR);
      @file = sort(@file);
      open(NF, ">file" || die "Cannot open file");

      foreach my $file (@file) {
      my $first_line = 1;
      open(FH, $file) or die "$!";
      while (<FH>) {
      chomp;
      if ((/Jan-\d\d/) || (/Feb-\d\d/) || (/Mar-\d\d/) || (/Apr-\d\d/) || (/May-\d\d/) || (/Jun-\d\d/) || (/Jul-\d\d/) || (/Aug-\d\d/) || (/Sep-\d\d/) || (/Oct-\d\d/) || (/Nov-\d\d/) || (/Dec-\d\d/)) {
      if ( $first_line ) {
      print NF $_;
      $first_line = 0;
      }
      else {
      print NF "\n$_";
      }
      }
      }
      }
      close(NF);
      close(FH);[/CODE]

      Comment

      • dh87lfc
        New Member
        • Oct 2007
        • 11

        #4
        I shall try that tomorrow. Thanks.

        Comment

        Working...