in reply to mimicing wc and split
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 | |
|
Re^2: mimicing wc and split
by dwhite20899 (Friar) on Oct 05, 2006 at 14:32 UTC |