Counting records separated by CR/LF (carriage return and newline) in Perl -


i'm trying create simple script read text file contains records of book titles. each record separated plain old double space (\r\n\r\n). need count how many records in file.

for example here input file:

record 1 text   record 2  text ... 

i'm using regex check carriage return , newline, fails match. doing wrong? i'm @ wits' end.

sub readinputfile {      $inputfile = $_[0]; #read first argument commandline filename      open inputfile, "+<", $inputfile or die $!;    #open file      $singleline;     @singlerecord;     $recordcounter = 0;      while (<inputfile>) {                    # loop through input file line-by-line         $singleline = $_;         push(@singlerecord, $singleline);    # start adding each line record array          if ($singleline =~ m/\r\n/) {        # check carriage return , new line             $recordcounter += 1;             createhashtable(@singlerecord);  # send record make hash table             @singlerecord = ();              # empty current record start new record         }      }      print "total records : $recordcounter \n";     close(inputfile); } 

it sounds processing windows text file on linux, in case want open file :crlf layer, convert crlf line-endings standard perl \n ending.

if reading windows files on windows platform conversion done you, , won't find crlf sequences in data have read. if reading linux file there no cr characters in there anyway.

it sounds records separated blank line. setting built-in input record separator variable $/ null string cause perl read whole record @ time.

i believe version of subroutine need. note people familiar perl thank using lower-case letters , underscore variables , subroutine names. mixed case conventionally reserved package names.

you don't show create_hash_table can't tell data needs. have chomped , split record lines, , passed list of lines in record newlines removed. better pass entire record single string , leave create_hash_table process required.

sub read_input_file {      ($input_file) = @_;      open $fh, '<:crlf', $input_file or die $!;     local $/ = '';      $record_counter = 0;      while (my $record = <$fh>) {         chomp;         ++$record_counter;         create_hash_table(split /\n/, $record);     }     close $fh;      print "total records : $record_counter\n"; } 

Comments

Popular posts from this blog

SPSS keyboard combination alters encoding -

Add new record to the table by click on the button in Microsoft Access -

javascript - jQuery .height() return 0 when visible but non-0 when hidden -