Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Hello, The code takes the two array values in parallel.
#!/usr/bin/perl my @filename = qw{filename1 filename2 filename3}; my @datas =qw{DATA1 DATA2}; my $i; $i=0; while($i < scalar(@filename)) { $count = `grep -c "$data[$i]" $filename[$i]`; print "$tags[$i]:$count\n"; $i++; }
How to print the grep command,
grep -c data1 filename1 grep -c data2 filename1 grep -c data1 filename2 grep -c data2 filename2 grep -c data1 filename3 grep -c data2 filename3
Please tell me how can I do this

Replies are listed 'Best First'.
Re: Print array values
by si_lence (Deacon) on Aug 10, 2009 at 11:11 UTC
    I'm not sure I understand your question right. If you want to see just the grep commands at the end of your post you can use somehing like this
    use strict; use warnings; my @filenames = qw{filename1 filename2 filename3}; my @datas =qw{DATA1 DATA2}; foreach my $filename (@filenames) { foreach my $data (@datas) { print "grep -c $data $filename \n"; } }
    to convert the DATA1 / DATA2 to lowercase is left as an exercise for the reader :-)
    cheers, si_lence
      Update: I had made an incorrect assumption on what the OP wanted, your are correct si_lence
Re: Print array values
by desemondo (Hermit) on Aug 10, 2009 at 12:01 UTC
    Based on the limited information you've provided I assume you wish to execute two grep statements per filename.

    But first, even though this might be a simple script, simple scripts have a habit of growing and evolving over time, so start it out properly at the beginning.
    use strict *ALWAYS*
    use warnings
    use a standard formatting and indentation style (i like K&R)

    Give this a try:
    #!/usr/bin/perl use strict; use warnings; my @filename = qw{filename1 filename2 filename3}; my @data =qw{DATA1 DATA2}; foreach my $file (@filename) { foreach my $searchdata (@data) { my $cmd_results = `grep -c $searchdata $file`; print "$file | $searchdata | $cmd_results \n"; # or whatever t +ags refers to... } }

    It may be worth noting that your original method would have run into problems once $i reaches 2 (and tries to process DATA3 which doesn't exist...)
    Using a foreach is nice since you don't need to care about an iterator, and you can make the code more self documenting... IMHO
Re: Print array values
by bichonfrise74 (Vicar) on Aug 10, 2009 at 23:56 UTC
    I wonder why you cannot just do a simple print command? What is wrong with this?
    while($i < scalar(@filename)) { ... print qq{grep -c "$datas[$i]" $filename[$i]\n}; ...
    And you might want to change your while loop into a for loop instead.
      If the array doesn't change size,
      my $i = 0; while ($i < @filename) { ... ++$i; }
      is a weird way of doing
      for my $i (0..$#filename) { ... }