in reply to Extract lines and output...

foreach( @files ) { my $outfile = outfile_name( $_ ); open( CUR, $_ ) or die "open $_: $!\n"; open( OUT, ">$outfile" ) or die "open $outfile: $!\n"; print OUT $_, "\n"; while( <CUR> ) { last if $. > 4; print OUT; } close( OUT ); close( CUR ); } sub outfile_name { my $base = shift; return $base . "_distilled" }

Replies are listed 'Best First'.
Re: Re: Extract lines and output...
by belden (Friar) on Oct 10, 2001 at 07:51 UTC
    Hi Fletch,

    I liked your approach. I'm not sure you need the sub in it
    though; you're already doing variable interpolation when you
    open( OUT, ">$outfile" ) or die ... so you could lean it up a bit:
    open( OUT, ">${_}_distilled" ) or die ...

    Here's what your code inspired me to do

    #!/usr/bin/perl for(glob '*') { /^$0$/ and next; # don't process the script open(I,"<$_") or die("$_: $!"); open(O,">$_.$$") or die("$_: $!"); print O $_,"\n"; { $. > 4 ? last : print O while(<I>); } close(I); } exit;

    While writing and subsequently edting above program I discov-
    ered the redundancy of local() in certain contexts. I originally wrote
    { local $_ = undef; $. > 4 ? last : print O while(<I>) }
    RRedundancy bad, so local went away.

    Update: changed >$outfile_distilled
    to ${_}_distilled which actually makes sense
    in the context of the original program.

    blyman

      If you like brief you might like this:
      #!/usr/bin/perl -w while(<*>) { next if /^$0$/; open I, $_ or die "$_: $!"; open O,">$_.bak" or die "$_.bak: $!"; print O $_, "\n", (<I>)[0..3]; close I, close O; }

      cheers

      tachyon

      s&&rsenoyhcatreve&&&s&n.+t&"$'$`$\"$\&"&ee&&y&srve&&d&&print

        Shorter still -
        open(LOG, ">logfile.txt"); while($FL = <*.extension>) { open(FL) and print LOG "$_\n",(<FL>)[0..3] and close(FL) } close(LOG);
        But we could golf this 'til the cows come home :o)
        HTH

        broquaint

        I like it really brief. The only reason I have close(I)
        is to reset $. You don't ever use $. so $. doesn't need to
        be reset - therefore the close calls aren't needed. This
        works just as well for me...
        #!/usr/bin/perl -w while(<*>) { next if /^$0$/; open I, $_ or die "$_: $!"; open O,">$_.bak" or die "$_.bak: $!"; print O $_, "\n", (<I>)[0..3]; #close I, close O; }
        A few things I picked up from your code:
        You used .bak instead of .$$, which makes your solution
        portable beyond *nix systems. I like your <*> more than my
        glob. Your treatment of the filehandle as though it were an
        array is also new to me.

        blyman