Help with perl script while reading a file


 
Thread Tools Search this Thread
Top Forums Shell Programming and Scripting Help with perl script while reading a file
# 8  
Old 05-25-2010
I don't know what you mean with "recend", I could not find this word in my dictionary, so I simply used a closing curly bracket (}) as the point where the script will skip reading the input file. It will start processing when it finds the string "_def:"
This is what I've done so far, but I think you will have to adjust it for your needs e.g. add standard length for file types which are not present in this header file. However it should at least give you some inspiration.
I don't know how it will perform when processing other header files...

Code:
$ cat nheader.h
//****************************************************************************
//
// sample.h       file definition
//
//****************************************************************************
//
//	
//
//

#ifndef ONE_H
#include <one.h>
#endif

abc
class sample_def:public user
{
	public:
//start of record layout--------------------------------------------------------
	char  name[23];		// Name 
	char  address[125]; 	// relevant address
	short age;  		// age
	short entries;		// no. of entries

	struct one
		{
			short age;		// end date
			float salary;		// min margin
		}value[10];

//end of record layout--------------------------------------------------------
	char  end;			// end of the record

/*********************************/
char *disp(char *two)
/*********************************/
{   
	return;
}

};


$

Code:
$ perl readhead.pl
$ 
$ cat nheader.csv
Name of the file: nheader.h
Id,Type,Size
name,char,23
address,char,125
age,short,2
entries,short,2
StructID,Type,Size
age,short,2
salary,float,4
$

Code:
#!/usr/bin/perl

use strict;
use warnings;

my @array1;
my @array2;
my $start=0;
my @elements;
my $size='';

my $infile='nheader.h';
my $outfile='nheader.csv';

open(INF,$infile) or die "Error opening infile $infile: $!\n";
my @array=<INF>;
close(INF);

foreach (@array) {
chomp;
push @array1, "$_\n" if $_ !~ /^\/\// && $_ !~ /^#/ && $_ !~ /^$/;
}

EXIT: foreach (@array1) {
chomp;

if ($_ =~ /_def:/)
{
$start=1;
next;
}
elsif ($start != 1)
{
next;
}
elsif ($_ =~ /}/)
{
last EXIT;
}
else
{
push @array2, "$_\n" if $_ !~ /{/ && $_ !~ /:/;
}

}

open(OUT,">$outfile") or die "Error opening outfile $outfile: $!\n";

print OUT "Name of the file: $infile\n";
print OUT "Id,Type,Size\n";

foreach (@array2) {
chomp;
$_ =~ s/\t//g;
$_ =~ s/;.*//g;
$_ =~ s/  / /g;

if ($_ =~ /\[/) {
@elements = split(/ /, $_);
my $type = $elements[0];
my $name = $elements[1];
my $size = $elements[1];
$name =~ s/\[.*//;
$size =~ s/.*\[//;
$size =~ s/\].*//;
print OUT "$name,$type,$size\n";
}
else {
@elements = split(/ /, $_);
if ($elements[0] eq "struct") {
print OUT "StructID,Type,Size\n";
next; }
if ($elements[0] eq "char") {
$size = 1; }
if ($elements[0] eq "short") {
$size = 2; }
if ($elements[0] eq "float") {
$size = 4; }
print OUT "$elements[1],$elements[0],$size\n";
}
}

close(OUT);

This User Gave Thanks to pseudocoder For This Post:
# 9  
Old 05-26-2010
Re:Thank you

Hi Pseudocoder, thanks a ton, for your help in resolving my problem. Your solution is the exact one that I was searching for. I could not have asked better than that.

In case of recend (record end), its just a word used in the header file, to notify that it is the end of the record. Sorry for not mentioning this in my previous post.

Once again, thanks very much.

Regards,
RB Smilie
# 10  
Old 05-31-2010
Re:Thank you

Hi Everyone, after help from pseudocoder and my struggle to achieve the desired output, I could finally parse a c++ file and pull out the data types and its related properties into a csv file. I am sharing the code snippet for anyone who may need it Smilie

Code:
# !/usr/bin/perl -w
# RB -- To print all the information of the data types and their sizes

use strict;
use warnings;

my @files = glob("*.h");                    #Get the list of all the header files in the directory
my $filename;
my($buffer) = "";
my $find = "_def:";                            #Read all the files which contain _def: (header files mapped to data files)
my $count = 0;
my @result;
my $recend="recend";                        #Read only till recend is encountered in the file
my $datafile = "DataFile_Information.csv";    #Output file
my $filecount = 0;
my $mVal;
my $size=1;
my $i;
my @comments;                                #Comments are populated seperately into this array
my $file;
my $comment_buffer;


open (FH, ">$datafile") or die "$!";

foreach $file (@files)
{
    $count = 0;
    ProcessHeaderFile($file);
}

print "\n\nSuccessfully processed $filecount files in the directory \n\n";


#Main subroutine to process each of the header file
#Only the ones which are mapped to the data file are read

sub ProcessHeaderFile
{
    $filename = $_[0];
    open(FILE, $filename) or die("Error reading file, stopped");
    my @inputfile = <FILE>;
    close(FILE);

    for(@inputfile)
    {
        if($_=~ /$find/)
        {
            $count = 1;
            $filecount += 1;
        }
    }
    
    open(FILE, $filename) or die("Error reading file, stopped");
    
    if ($count == 1)
    {
        print FH "\n\n\U ***** Filename: $filename *****\n\n";
        print FH "Id,Type,Size,Comments\n";
        until(eof FILE)
        {
            @comments="";
            
            $buffer = readline( *FILE );
            $comment_buffer = $buffer;

            if($buffer =~ /$recend/)
            {
                return;
            }
            
            if ($buffer =~ m/char|short|int|float|BYTE|struct/i)
            {
                
                @comments = split('//',$comment_buffer);
                if(!($comments[1]))
                {
                    $comments[1] = ",";
                }

                #split the entire line to get the required values in a formatted way        
                chomp($buffer);
                $buffer =~ s/\]//g;
                $buffer =~ s/\[/,/g;
                $buffer =~ s/;/,/;
                $buffer =~ s/\//,/;
                $buffer =~ s/\//,/;
                $buffer =~ s/ /,/;
                $buffer =~ s/\t/,/g;
                $buffer =~ s/^,+//; #Remove leading comma's
                $buffer =~ s/[,][,]*/,/g; #Remove extra comma's
                $buffer =~ s/ //g;
        
                @result  = split ',',$buffer;

                my $bool = 1;
                if ($result[0] eq "char")
                {
                    $mVal = 1;
                }
                elsif ($result[0] eq "short")
                {
                    $mVal = 2;
                }
                elsif ($result[0] eq "int")
                {
                    $mVal = 4;
                }
                elsif ($result[0] eq "float")
                {
                    $mVal = 4;
                }
                elsif ($result[0] eq "BYTE")
                {
                    $mVal = 1;
                }
                elsif ($result[0] eq "struct")
                {
                    $mVal = 0;
                    print FH "StructID,Type,Size,Comments\n";
                }
                else
                {
                    $bool = 0;
                }

                if($bool)
                {
                    $size = 1;
                
                    foreach $i (@result)
                    {
                        if ($i =~ m/^-?\d+$/)
                        {
                            $size = $size * $i;
                        }
                        else
                        {
                                $size = $mVal;
                        }
                    }
                    
                    $size = $size * $mVal;

                    #Print the final values to the output file
                    print FH "$result[1],$result[0],$size,$comments[1] \n";
                }
                else
                {
                    print FH ",,,@result \n";
                }
            }        
        }
    }
close(FILE);
}
close(FH);

Regards,
RB Smilie
Login or Register to Ask a Question

Previous Thread | Next Thread

10 More Discussions You Might Find Interesting

1. Shell Programming and Scripting

Error while reading variable from a file in perl script

I have a file abc.ini and declared many variables in that file, one of the variable(DBname) value I am trying to read in my perl script but getting error. File abc.ini content # database name DBname =UATBOX my $ex_stat; my $cmd_output; $ex_stat = "\Qawk '/^DBname/{print... (2 Replies)
Discussion started by: Devesh5683
2 Replies

2. Shell Programming and Scripting

Need help with perl script with a while loop reading file

Good morning, I appreciate any assistance that I can get from the monks out there. I am able to get this to work for me so that I can do a hostname lookup if I only specify one hostname in the script. What I want to do is have a file with hostnames and do lookups for each name in the file. Here is... (1 Reply)
Discussion started by: brianjb
1 Replies

3. Shell Programming and Scripting

Perl Script for reading table format data from file.

Hi, i need a perl script which reads the file, content is given below. and output in new file. TARGET DRIVE IO1 IO2 IO3 IO4 IO5 ------------ --------- --------- --------- --------- --------- 0a.1.8 266 236 ... (3 Replies)
Discussion started by: asak
3 Replies

4. UNIX for Dummies Questions & Answers

reading a file in Perl

If a form's action is the following Perl script how do I make it print the entire contents of the file on the screen? if(param()) { my $uploadedFile = param('file');#in the html page 'file' is the value of the name attribute of the input my $fh = upload($uploadedFile); ... (1 Reply)
Discussion started by: zerohour
1 Replies

5. Shell Programming and Scripting

Perl Script Not Reading Input Files Correctly

This is one of the strangest things that's happening to me. I'm writing a new Perl script that is trying to read a file. The file is originally in .mof format, but I also saved the contents into a .txt file. As a simple test, I wrote this: #!/user/bin/perl -w use strict; ... (3 Replies)
Discussion started by: kooshi
3 Replies

6. Shell Programming and Scripting

Help need in perl script reading from file

Need perl script, data file will be csv format. I have text file contains 2 colums. Filename Foldernumber aaaa 13455 bbbb 23465 cccc 26689 I have two location 1. files present and 2. folders present. I need to search for file and folder if folder... (3 Replies)
Discussion started by: hnkumar
3 Replies

7. Shell Programming and Scripting

SOLVED: reading config file in a perl script

Hi! I have a need to do this in Perl. script.pl -config file The script would be doing a wget/LWP on a URL which is defined in the config file. So when I run the script it should return either one of these conditions - 1) OK with exit status 0. Should also print "wget URL" 2)... (6 Replies)
Discussion started by: jacki
6 Replies

8. Shell Programming and Scripting

perl - reading from a file conditionally

Hi, I am new to perl. I want to read from a file on the basis of some conditions.. I want to define parameters in a configuration file in such a manner like... etc.. in my perl script, theer is a variable like this.. then i want to read values from first if block from the file... (1 Reply)
Discussion started by: shellwell
1 Replies

9. Shell Programming and Scripting

Reading each line of a file in perl script

HI I need to read each line (test.txt) and store it in a array (@test) How to do it in perl. Suppose i have a file test.txt. I have to read each line of the test.txt file and store it in a array @test. How to do it in perl. Regards Harikrishna (3 Replies)
Discussion started by: Harikrishna
3 Replies

10. Shell Programming and Scripting

Perl Reading from File

is there a perl equivalent to sscanf? or something where I get the strings separated by spaces? (1 Reply)
Discussion started by: karyn1617
1 Replies
Login or Register to Ask a Question