in reply to usage of awk and grep together

Anything awk/grep can do perl can do better! You don't need to inefficiently call them externally, perl already has adopted their strengths.

sub get_log_data { open my $logfile, '<', 'logfile' or die "open on logfile: $!"; my @data_lines; while (<$logfile>) { next unless ( /fileid/ .. /^-{5}/ ); # range operator! if (/specificdata/) { push @data_lines, $_; } } close $logfile; die 'could not find specificdata in logfile' unless (@data_lines); return join q{}, @data_lines; }

Please try to enclose your code and error message in <c> and </c> tags in the future. Your error did not display right and the code is easier to read with these tags.

Update: fixed bug where only one line of specificdata matching would be returned, not multiple lines.

Replies are listed 'Best First'.
Re^2: usage of awk and grep together
by JavaFan (Canon) on May 20, 2009 at 08:19 UTC
    Anything awk/grep can do perl can do better!
    Suggesting a 15 line sub as alternative for a short one liner doesn't present anything in support of your claim.
Re^2: usage of awk and grep together
by raghu_shekar (Novice) on May 20, 2009 at 06:33 UTC
    Hi, Thanks, but im very very new to perl. the fileid and the specific data in the code are also stored in an array. i pick them from an array store them in a variable and substitute them in the command. Also i am not familiar with shell scripting.

      I would suggest playing with creating subs and passing them arguments if you haven't already. Like this example you can take code you already have and put them in a nice friendly named container. This is a fundamental skill that is very handy.

      Call the sub with just the $fileid and $specificdata that you want given as arguments.

      You retrieve the arguments very easily:

      sub get_log_data { my ($fileid, $match) = @_; #...

      Then just replace fileid with $fileid and specificdata with $match.

      As you can see there are many other ways to do this. I provided the longest way I could think of because I hoped it would be easier to understand and learn from. Short one-liners generally have many subtle concepts that make them work. i.e. here is the sub using johngg's approach, one I would use for a quick n dirty script.

      sub get_log_data { my ($fileid, $match) = @_; local @ARGV = 'logfile'; return join '', grep { (/$fileid/o .. /\A-{5}/) && /$match/o } <>; }

      I'd suggest using a long, explicit, easy to debug, easy to understand version for a beginner; as a learning exercise.