in reply to Not exactly Dereferencing... but in that ball park

Looks like you need hash subscripting instead of the symbolic referencing you're gesturing at.

my @message_type=('error','alert','warning'); my %messages; my $messages_log='/var/log/messages'; foreach (@message_type) { $messages{$_}=`cat $messages_log |grep $_ | wc -l`; chomp($messages{$_}); $messages{$_}=~s/ //g; }

Replies are listed 'Best First'.
Re^2: Not exactly Dereferencing... but in that ball park
by Roy Johnson (Monsignor) on Nov 19, 2005 at 21:27 UTC
    And then turn it into a Perl script instead of a shell script written in Perl.
    my @message_type=('error','alert','warning'); my %messages; my $messages_log='/var/log/messages'; open LOG, $messages_log or die "$!: $messages_log\n"; while (<LOG>) { foreach my $msg_type (@message_type) { ++$messages{$_} if /\Q$msg_type/; } } close LOG;

    Caution: Contents may have been coded under pressure.
      Well okay, but I think the OP wanted to partition messages by type, not count instances. So to perlify further:

      my %messages = map { $_ => [] } qw(error alert warning); my $logfile = '/var/log/messages'; open my $log, "<", $logfile or die "$logfile: open: $!"; while (<$log>) { for my $type (keys %messages) { push @{ $messages{$type} }, $_ if /$type/; } } close $log or die "$logfile: close: $!"; # as long as we're bothering +with explicit close, we may as well test it for success.

      I know you know it, but there's no reason to \Q the type names here since they don't contain dangerous characters.

        Actually, based on the OP's code, where they're using "wc -l", they want a count. cat file | grep something | wc -l is the shell way to count the number of lines that match. Well, grep -c would probably be a bit more efficient. As would avoiding cat: grep -c something file. One process rather than three. Regardless, that's what the OP's code does.

        As for the \Q, it's just a handy habit to be in. It's more likely to do what the programmer wants, which is why perl 6's default will be to match variables exactly, and require putting them in angle brackets to treat them as regexp strings to be parsed and matched.