in reply to mimicing wc and split

The previous replies are more worth pursuing than mine, but just to be picky, I'll point out:

To emulate unix "wc -l", you should accept data from STDIN, and you should accept multiple file name args on the command line, reporting the line count for each file in succession:

#!/usr/bin/perl -w use strict; if ( @ARGV ) { for my $file ( @ARGV ) { $. = 0; open( I, $file ) or do { warn "$0: open failed for file $file: $!\n"; next; } while (<I>) {} printf( "%8d %s\n", $., $file ); } } else { while (<>) {} printf( "%8d\n", $. ); }

As for your version of "split", the only thing I see wrong is that if the line count of an input file happens to be a multiple of the selected line count for output, you'll open an extra file for output, and will close it without having written anything to it. No big deal, except some users might get confused, misled or even tripped up by having an extra file (which happens to be empty) when the process is done. Here's a simplified version that avoids that problem:

#!/usr/bin/perl -w use strict; my $Usage = "Usage: $0 line_count input.file output_name\n"; ( @ARGV == 3 and $ARGV[0] =~ /^\d+$/ and -f $ARGV[1] ) or die $Usage; my ( $line_limit, $infile, $outname ) = @ARGV; my $outid = 0; open( I, $infile ) or die "$0: open for input failed on $infile: $!\n$ +Usage"; while (<IN>) { if ( $. % $line_limit == 1 ) { close OUT if ( $outid ); my $outfile = sprintf( "%s.%03d", $outname, ++$outid ); open( OUT, ">", $outfile ) or die "$0: open for output failed +on $outfile\n"; } print OUT; } close OUT;

Replies are listed 'Best First'.
Re^2: mimicing wc and split
by shmem (Chancellor) on Oct 05, 2006 at 07:01 UTC
    syntax error at 576460.pl line 11, near ") {" syntax error at 576460.pl line 14, near "}" Execution of 576460.pl aborted due to compilation errors.

    missig ; after the do{} block in wc. Didn't test? ;-)

    #!/usr/bin/perl -w use strict; my ($i,$c) = @ARGV > 1 ? 8 : 0; (-z $ARGV[0] and printf ("%${i}d %s\n", 0, shift) and @ARGV or exit) +if @ARGV; while(<ARGV> || eof ARGV) { $c++; if (eof(ARGV)) { printf "%${i}d %s\n", $., $ARGV; $. = 0; $ARGV[0] and -z $ARGV[0] and printf "%${i}d %s\n", 0, shift; @ARGV || last; } } printf "%${i}d total\n",$c if $i;

    --shmem

    _($_=" "x(1<<5)."?\n".q·/)Oo.  G°\        /
                                  /\_¯/(q    /
    ----------------------------  \__(m.====·.(_("always off the crowd"))."·
    ");sub _{s./.($e="'Itrs `mnsgdq Gdbj O`qkdq")=~y/"-y/#-z/;$e.e && print}
Re^2: mimicing wc and split
by dwhite20899 (Friar) on Oct 05, 2006 at 14:32 UTC
    Argh! Yep, I didn't think about a file the size of the split block. Thanks for the nice catch.