2

I am writing a perl script to parse a 'c' header file and extract enumeration types and their respective members.

  • Ubuntu 12.04
  • Perl 5.14.2

The perl script seems to work, but in some circumstances some of the variables will not print. I've stripped down the code to the following minimal duplication.

I'm pretty sure this has something to do with buffering... because if I add a newline between printing the first variable and the other variables it works.

I did read through suffering from buffering and Perl not printing properly, without finding a solution to my own issue.

Here's the header file:

 #ifndef _ENUM_H_
 #define _ENUM_H_ 1

 /**
  * Enum definition
  */
 typedef enum
 {
    eENUMVAL0 = 0,
    eENUMVAL1,
    eENUMVAL2,
    eENUMVAL_LAST,
 } eMySuperEnum;

 #endif /* _ENUM_H_ */

And here's the script:

 #! /usr/bin/perl
 use strict;
 use warnings;


 our  @apiFile = ();


 if (exists $ARGV[0])
 {
     chomp( @apiFile = `cat $ARGV[0]`);
 }

 for my $i (0 .. $#apiFile)
 {
     if ($apiFile[$i] =~ /^\s*typedef\s+enum/)
     {
         print "$apiFile[$i] starts at $i\n"; 
     }
 }

This prints:

starts at 6

But if I add a newline in the print after $apiFile[$i], then it prints the whole thing:

print "$apiFile[$i]\nstarts at $i\n";

Will print:

typedef enum
starts at 6

I have many times printed multiple variables on the same line. What is happening under the hood such that perl is not printing these two variables on a single line?

Community
  • 1
  • 1
guidotex
  • 183
  • 2
  • 10
  • 5
    Does the input file come from windows by any chance? It might be including a stray `\r` that screws up printing. – Sobrique May 09 '17 at 14:21
  • 3
    `$apiFile[$i]` contains a CR(carrage return), so the Cursor will be set to the beginning of the line – Jens May 09 '17 at 14:22

1 Answers1

8

Best guess would be - the source file has come through Windows, and is including spurious carriage returns.

chomp doesn't handle this if it's on Linux.

But you can use s to replace:

s/[\r\n]+$//g; will work in lieu of chomp;

Sobrique
  • 52,974
  • 7
  • 60
  • 101
  • 4
    Or if you don't feel like fixing the perl script, run `dos2unix` on the input files. – Mr. Llama May 09 '17 at 14:30
  • 1
    Or ,`s/\R+//g`. – Sinan Ünür May 09 '17 at 14:42
  • 1
    This worked. I had just started to think there was an unseen character that was affecting the printing. It is a file in Linux, so I did not expect this. However, the API header that I am parsing was written on a windows machine by a third party... so I checked it in vim via "set ff?" Sure enough "ff = dos", so there you go. :) – guidotex May 09 '17 at 14:47