gfarhat has asked for the wisdom of the Perl Monks concerning the following question:

how can i verify if all lines in a textfile have this format:

name:some_name,version:some_number,date:xx/xx/xx

Replies are listed 'Best First'.
Re: string format validation
by Skeeve (Parson) on Mar 27, 2008 at 15:39 UTC

    You can verify that by using regular expressions.

    while (<>) { if (! m#^name:some_name,version:some_number,date:xx/xx/xx$#) { warn "Line $. doesn't fit\n" } }

    Of course you need to change the RE to fit your needs.


    s$$([},&%#}/&/]+}%&{})*;#$&&s&&$^X.($'^"%]=\&(|?*{%
    +.+=%;.#_}\&"^"-+%*).}%:##%}={~=~:.")&e&&s""`$''`"e
Re: string format validation
by mr_mischief (Monsignor) on Mar 27, 2008 at 15:51 UTC
    This smells like homework. It's polite if that's the case to say so and the monks can give guidance instead of an answer to a homework problem. I'll give you the benefit of the doubt, though.

    while ( <> ) { m{ name:[\w\.\-\s]+ , version:(?:\+|-)?\d*\.?\d* , date:\d{2}/\d{2}/\d{2} }x or print "Does not match on line $..\n"; }

    You can check out perlre (or just perldoc perlre on must Unixy-type OSes) to find more information on what the different parts of that mean.

Re: string format validation
by Corion (Patriarch) on Mar 27, 2008 at 15:37 UTC

    One approach would be to look at every line of the file and inspect that that line matches. A Perl program to inspect a certain line of a file would be:

    use strict; use Tie::File; my $f = shift; my $l = shift -1; tie my @f => 'Tie::File' => $f; print "$l: $f[$l]";

    Save that program as a file and then invoke it for every line:

    perl -w gfarhat.pl testfile.txt 1 perl -w gfarhat.pl testfile.txt 2 ... perl -w gfarhat.pl testfile.txt 9998

    You can golf the above program into the following, if the overhead of creating a Perl program is too much for you:

    perl -nle 'BEGIN{$l=pop}print if $.==$l' testfile.txt 1
Re: string format validation
by ikegami (Patriarch) on Mar 27, 2008 at 17:03 UTC
    That's a rather odd format. Why put the field names in every record? It's rather redundant unless the fields are optional. If that's the case, the solutions provided by our fellow monks will need to be amended.
Re: string format validation
by Anonymous Monk on Mar 27, 2008 at 15:41 UTC
    perl -ne'm|name:\w+,version:\d+,date:\d\d/\d\d/\d\d| or warn "$.:Malformed line: $_\n"' thefile