Also how do i find the number of lines in a file(text or any flatfile?)

I didn't see an answer to this part of the question in the replies, so here goes: (Choose the one that fits best into your program.)

sub get_num_lines_method1 { my ($file_name) = @_; my $num_lines = 0; local *FILE; open(FILE, $file_name); $num_lines++ while (<FILE>); close(FILE); return $num_lines; } sub get_num_lines_method2 { # Really same as get_num_lines_method1. my ($file_name) = @_; my $num_lines = 0; local *FILE; open(FILE, $file_name); while (<FILE>) { $num_lines++; } close(FILE); return $num_lines; } sub get_num_lines_method3 { # Loads the whole file into an array. my ($file_name) = @_; local *FILE; open(FILE, $file_name); my @file = <FILE>; close(FILE); return scalar(@file); } sub get_num_lines_method4 { # Loads the whole file into a scalar. my ($file_name) = @_; local *FILE; open(FILE, $file_name); local $/; my $file = <FILE>; close(FILE); return $file =~ tr/\n/\n/; } printf("Method 1: %d\n", get_num_lines_method1($0)); printf("Method 2: %d\n", get_num_lines_method2($0)); printf("Method 3: %d\n", get_num_lines_method3($0)); printf("Method 4: %d\n", get_num_lines_method4($0)); __END__ output: ======= Method 1: 62 Method 2: 62 Method 3: 62 Method 4: 62

Update: None of the methods count the empty string between the last \n and the EOF as a line. Method 4 will not count a non-empty string between the last \n and the EOF as a line, although it should and could be modified to do so.


In reply to Re: Tricky Problem by ikegami
in thread Tricky Problem by perl_krish

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.