in reply to Extract first word from certain lines in a file

I am sorry if I did not state the question clearly. Actrully I want to get the first word of each lines of each product:
We can see the output values can be:
Product 1:
redball,greenball
smallbox,bigbox

Hopefully this time will be better!

  • Comment on Re: Extract first word from certain lines in a file

Replies are listed 'Best First'.
Re^2: Extract first word from certain lines in a file
by ikegami (Patriarch) on Oct 25, 2004 at 21:59 UTC
    sub dump_product { my ($product) = @_; print(join(', ', @$product), $/) if (@$product); @$product = (); } my @product; while (<DATA>) { if (/^Product\b/) { dump_product(\@product); } elsif (/^(\S+)/) { push(@product, $1); } } dump_product(\@product); __DATA__ Product: redball This is for Mike. greenball This is for Dave. Product: smallbox This is for apples bigbox This is for orange

    output:

    redball, greenball smallbox, bigbox
Re^2: Extract first word from certain lines in a file
by CountZero (Bishop) on Oct 25, 2004 at 21:54 UTC
    That is easy:
    use strict; while ( <DATA> ) { do {print "\n"; next} if /Product:/; my $firstword=(split " ")[0]; print "$firstword "; } __DATA__ Product: redball This is for Mike. greenball This is for Dave. Product: smallbox This is for apples bigbox This is for orange

    CountZero

    "If you have four groups working on a compiler, you'll get a 4-pass compiler." - Conway's Law

Re^2: Extract first word from certain lines in a file
by borisz (Canon) on Oct 25, 2004 at 22:29 UTC
    my (@w, $c); local ( $", $_ ) = ", "; do { $_ = <DATA>; if ( defined $_ && !/^Product:/ ) { push @w,(split ' ')[0]; } elsif ( @w ) { print "Product: ", ++$c, "\n@w\n"; @w = (); } } while ( defined $_ ); __DATA__ Product: redball This is for Mike. greenball This is for Dave. Product: smallbox This is for apples bigbox This is for orange
    output:
    Product: 1 redball, greenball Product: 2 smallbox, bigbox
    Boris
      I was wondering why you use local ( $", $_ ) = ", "; since there is no enclosing scope other than the script file itself. The local does not seem to serve any purpose.

      CountZero

      "If you have four groups working on a compiler, you'll get a 4-pass compiler." - Conway's Law

        I t is just good habit.
        Boris