How do I find the length of the longest line in a file?

Discussion in 'Perl Misc' started by John Howard, Aug 13, 2005.

  1. John Howard

    John Howard Guest

    I'm not that great a perl programmer. Just know the basics.

    I need some sample code to show me how to read a file and find the
    length of the longest line in the file.

    Thanks in advance.
    John Howard, Aug 13, 2005
    #1
    1. Advertising

  2. John Howard

    Juha Laiho Guest

    "John Howard" <> said:
    >I'm not that great a perl programmer. Just know the basics.
    >
    >I need some sample code to show me how to read a file and find the
    >length of the longest line in the file.


    How about thinking what needs to be done to achieve that - then
    transform the thoughts into a program? I'll walk you through the
    first part.

    Very rough:
    Looks like one variable is needed: the place to hold length of
    longest line seen so far.

    The file must be read a line at a time, comparing length of
    each line to the length of longest line seen so far.

    When all the lines have been read, the length of the longest
    line is to be printed.

    Adding some finer points to the above, and changing the wording
    towards a computer program:
    - declare a variable (let's call it $longest), initialize it to '-1'
    - attempt to open the file, storing the error status (if any)
    - if file open succeeded
    - for the following lines ...
    - read a line
    - if length of line is greater than value stored in $longest,
    store length of line to $longest
    - ... repeat until end of file is reached

    - if value of $longest is still '-1', output the error message
    describing why the file opening failed
    - otherwise, print a message telling that length of the longest
    line in the file was $longest

    .... and even now I feel I've been helping you all too much with
    your homework.
    --
    Wolf a.k.a. Juha Laiho Espoo, Finland
    (GC 3.0) GIT d- s+: a C++ ULSH++++$ P++@ L+++ E- W+$@ N++ !K w !O !M V
    PS(+) PE Y+ PGP(+) t- 5 !X R !tv b+ !DI D G e+ h---- r+++ y++++
    "...cancel my subscription to the resurrection!" (Jim Morrison)
    Juha Laiho, Aug 13, 2005
    #2
    1. Advertising

  3. John Howard wrote:
    > I'm not that great a perl programmer. Just know the basics.
    >
    > I need some sample code to show me how to read a file and find the
    > length of the longest line in the file.
    >
    > Thanks in advance.


    awk 'length($0)>m{m=length($0)}END{print m}' somefile.txt
    William James, Aug 13, 2005
    #3
  4. John Howard

    James Taylor Guest

    In article <>,
    William James <> wrote:
    >
    > John Howard wrote:
    > > I need some sample code to show me how to read a file and find the
    > > length of the longest line in the file.

    >
    > awk 'length($0)>m{m=length($0)}END{print m}' somefile.txt


    Perl supports awkish syntax too:

    perl -ne '$m=length if $m<length; END{print $m}' somefile.txt

    --
    James Taylor, London, UK PGP key: 3FBE1BF9
    To protect against spam, the address in the "From:" header is not valid.
    In any case, you should reply to the group so that everyone can benefit.
    If you must send me a private email, use james at oakseed demon co uk.
    James Taylor, Aug 13, 2005
    #4
  5. John Howard wrote:
    > I'm not that great a perl programmer. Just know the basics.
    >
    > I need some sample code to show me how to read a file and find the
    > length of the longest line in the file.



    my $file = 'somefile.txt';

    open my $fh, '<', $file or die "Cannot open $file: $!";

    my $longest;

    while ( <$fh> ) {

    $longest = length if $longest < length;
    }

    print "The longest line is $longest bytes.\n";




    John
    --
    use Perl;
    program
    fulfillment
    John W. Krahn, Aug 14, 2005
    #5
  6. James Taylor wrote:

    > Perl supports awkish syntax too:
    >
    > perl -ne '$m=length if $m<length; END{print $m}' somefile.txt


    Good point. Since "computer golf" is so much fun, here's my
    solution in Ruby (I tried the awkish approach, but this is
    shorter):

    ruby -e 'p ARGF.map{|x|x.size}.max-1' somefile.txt

    The -1 is there because of the trailing linefeed characters.
    William James, Aug 14, 2005
    #6
  7. Juha Laiho wrote:

    > Very rough:
    > Looks like one variable is needed: the place to hold length of
    > longest line seen so far.

    [...]
    > - declare a variable (let's call it $longest), initialize it to '-1'


    <Nitpicking mode>
    IMHO, a "length" is _always_ positive, especially if it refers to
    lengths of text-lines, so '-1' would be an illegal value.
    I'd either leave it undef-ined (which would fit if you haven't seen any
    lines yet) or set it to 0 (if you haven't seen anything, you have seen 0).
    </Nitpicking mode>

    --
    Josef Möllers (Pinguinpfleger bei FSC)
    If failure had no penalty success would not be a prize
    -- T. Pratchett
    Josef Moellers, Aug 15, 2005
    #7
  8. John Howard

    James Taylor Guest

    In article <>,
    William James <URL:mailto:> wrote:
    >
    > James Taylor wrote:
    > >
    > > Perl supports awkish syntax too:
    > >
    > > perl -ne '$m=length if $m<length; END{print $m}' somefile.txt

    >
    > Good point. Since "computer golf" is so much fun, here's my
    > solution in Ruby (I tried the awkish approach, but this is
    > shorter):
    >
    > ruby -e 'p ARGF.map{|x|x.size}.max-1' somefile.txt


    Is ARGF an array of lines of the files supplied on the command line
    in a similar way to Perl's <> handle?

    Doesn't Ruby's map method have the equivalent of Perl's anonymous
    scalar? In Perl you might write:

    @line_lengths = map length, <>;

    without having to name a variable x *twice* as in your example.
    So, just hand waving here, Ruby might write: AGRF.map{.size}
    or similar.

    PS. Is there any great motivation for your Ruby advocacy when we'll
    all someday be sharing the Parrot runtime anyway? Seems to me the
    main motivation for advocacy of one language over another would be
    because you want more people to contribute to your favourite language's
    codebase in the same way that Perl gains so much from CPAN contributions.
    With Parrot, the language war is over because everyone's contributions
    will work together regardless of the language they're written in.
    So, I can't help feeling your efforts would be better directed in
    the comp.lang.ruby group, rather than here. Ruby has too much in
    common with Perl for it to be worthwhile any of us learning it if
    we're already happy with Perl and, until Parrot is widely available,
    CPAN tips the usefulness in favour of Perl anyway. Sure, you've shown
    us that Ruby is cute, expressive, and powerful, but that's just
    not enough for most people.

    --
    James Taylor, London, UK PGP key: 3FBE1BF9
    To protect against spam, the address in the "From:" header is not valid.
    In any case, you should reply to the group so that everyone can benefit.
    If you must send me a private email, use james at oakseed demon co uk.
    James Taylor, Aug 15, 2005
    #8
  9. John Howard

    Anno Siegel Guest

    Josef Moellers <> wrote in comp.lang.perl.misc:
    > Juha Laiho wrote:
    >
    > > Very rough:
    > > Looks like one variable is needed: the place to hold length of
    > > longest line seen so far.

    > [...]
    > > - declare a variable (let's call it $longest), initialize it to '-1'

    >
    > <Nitpicking mode>
    > IMHO, a "length" is _always_ positive, especially if it refers to
    > lengths of text-lines, so '-1' would be an illegal value.


    Quite. Since -1 cannot be the length of any actual line, it serves
    well to indicate the fact that no actual line has been seen yet.

    > I'd either leave it undef-ined (which would fit if you haven't seen any
    > lines yet) or set it to 0 (if you haven't seen anything, you have seen 0).
    > </Nitpicking mode>


    Not so. You have seen 0 lines, but not a line of length 0, so you
    have no reason to set the minimum length to any legal value, not even 0.

    In practice, initializing the minimum to 0 would make the cases
    indistinguishable where you have no lines at all and where you have
    one or more lines all of length 0.

    Using undef instead of -1 is of course okay (it is also not the length
    of any line), but -1 makes the numeric treatment easier.

    Anno
    --
    If you want to post a followup via groups.google.com, don't use
    the broken "Reply" link at the bottom of the article. Click on
    "show options" at the top of the article, then click on the
    "Reply" at the bottom of the article headers.
    Anno Siegel, Aug 15, 2005
    #9
  10. John Howard

    Guest

    James Taylor <> wrote:
    > Doesn't Ruby's map method have the equivalent of Perl's anonymous
    > scalar? In Perl you might write:


    Who is Ruby and why should I wave to her... unless she
    is a good-looking redhead which I doubt.

    Axel
    , Aug 15, 2005
    #10
  11. John Howard

    John Howard Guest

    John W. Krahn wrote:
    > John Howard wrote:
    > > I'm not that great a perl programmer. Just know the basics.
    > >
    > > I need some sample code to show me how to read a file and find the
    > > length of the longest line in the file.

    >
    >
    > my $file = 'somefile.txt';
    >
    > open my $fh, '<', $file or die "Cannot open $file: $!";
    >
    > my $longest;
    >
    > while ( <$fh> ) {
    >
    > $longest = length if $longest < length;
    > }
    >
    > print "The longest line is $longest bytes.\n";


    I ended up using a variant of this. Thanks. I didn't realise "length"
    was the required function (the perl docs are rather hard to fathom. I
    kept looking for something like strlen etc. Oh well).

    Can it also be use for a field in a file? I.e. read the lines into
    local vars using split and then check the length of one of those?
    John Howard, Aug 19, 2005
    #11
  12. John Howard

    Paul Lalli Guest

    John Howard wrote:

    > I ended up using a variant of this. Thanks. I didn't realise "length"
    > was the required function (the perl docs are rather hard to fathom. I
    > kept looking for something like strlen etc. Oh well).


    They take some getting used to, I admit, but once you know how to work
    them, I think it's generally pretty easy to find what you're looking
    for. In this case:
    perldoc perlfunc
    would have given you a listing of all Perl functions, including a
    section on Perl Functions by Category. The first category listed is
    "Functions for SCALARs or strings", and length is near the beginning of
    that list.

    See also:
    perldoc perltoc
    for a full Table Of Contets of the Perl documentation.

    > Can it also be use for a field in a file? I.e. read the lines into
    > local vars using split and then check the length of one of those?


    If I understand your question correctly, yes. length returns the
    length in bytes of its argument. If no argument is provided, it
    returns the length of the current value of $_.

    #!/usr/bin/perl
    use strict;
    use warnings;
    my $foo = "a bunch of word characters";
    my @words = split / /, $foo;
    for my $word (@words){
    print "The length of '$word' is: ", length $word, "\n";
    }
    __END__

    The length of 'a' is: 1
    The length of 'bunch' is: 5
    The length of 'of' is: 2
    The length of 'word' is: 4
    The length of 'characters' is: 10


    Paul Lalli
    Paul Lalli, Aug 19, 2005
    #12
  13. John Howard wrote:
    [Solution snipped]
    > I ended up using a variant of this. Thanks. I didn't realise "length"
    > was the required function (the perl docs are rather hard to fathom. I
    > kept looking for something like strlen etc. Oh well).


    Two notes:
    - "How do I get the length of a string?" is the best known SAQ (Self
    Answering Question) in the Perl community. There are many old threads about
    it. Granted, it hasn't been asked for while now.
    - You know about "perldoc perlfunc", section "Perl Functions by Category",
    don't you?

    Functions for SCALARs or strings
    "chomp", "chop", "chr", "crypt", "hex", "index", "lc", "lcfirst",
    "length", "oct", "ord", "pack", "q/STRING/", "qq/STRING/",
    "reverse", "rindex", "sprintf", "substr", "tr///", "uc", "ucfirst",
    "y///"

    > Can it also be use for a field in a file? I.e. read the lines into
    > local vars using split and then check the length of one of those?


    In which way are "fields" different then "strings"?

    jue
    Jürgen Exner, Aug 19, 2005
    #13
  14. Paul Lalli wrote:
    > If I understand your question correctly, yes. length returns the
    > length in bytes of its argument.


    That would be a really bad bug. From "perldoc -f lenght":

    length Returns the length in characters of the value of EXPR.

    jue
    Jürgen Exner, Aug 19, 2005
    #14
  15. John Howard

    Paul Lalli Guest

    Jürgen Exner wrote:
    > Paul Lalli wrote:
    > > If I understand your question correctly, yes. length returns the
    > > length in bytes of its argument.

    >
    > That would be a really bad bug. From "perldoc -f lenght":
    >
    > length Returns the length in characters of the value of EXPR.


    Whoops. My mistake. Thanks for the correction, Jürgen.

    Paul Lalli
    Paul Lalli, Aug 19, 2005
    #15
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Replies:
    2
    Views:
    361
  2. longhorn

    How to find longest bitrange of ones

    longhorn, May 7, 2008, in forum: C Programming
    Replies:
    2
    Views:
    242
    Willem
    May 7, 2008
  3. scad
    Replies:
    23
    Views:
    1,155
    Alf P. Steinbach
    May 17, 2009
  4. Sam

    length of the longest $_ in @_

    Sam, Sep 22, 2003, in forum: Perl Misc
    Replies:
    15
    Views:
    182
    Jay Tilton
    Sep 23, 2003
  5. Csaba  Gabor

    Length of longest contiguous digits exercise

    Csaba Gabor, Oct 23, 2009, in forum: Javascript
    Replies:
    19
    Views:
    184
Loading...

Share This Page