http://qs321.pair.com?node_id=900609


in reply to Re^2: Comparing two arrays...
in thread Comparing two arrays...

I did test it (see code below). It seemed to work for me but I see from some of the comments that it can be used in a much better way.

#!/usr/bin/perl -w use strict; my @ServicesOnMachine = qw(NetworkManager acpid anacron atd auditd aut +ofs avahi-daemon avahi-dnsconfd bluetooth capi conman cpuspeed crond +cups dnsmasq dund firstboot gpm haldaemon hidd hplip httpd ip6tables +iptables irda irqbalance iscsi iscsid isdn kudzu lvm2-monitor mcstran +s mdmonitor mdmpd messagebus multipathd netconsole netfs netplugd net +work nfs nfslock nscd ntpd oddjobd pand pcscd portmap psacct rawdevic +es rdisc readahead_early readahead_later restorecond rpcgssd rpcidmap +d rpcsvcgssd saslauthd sendmail smartd sshd svnserve syslog tcsd vbox +add vboxadd-service vboxadd-x11 vncserver wdaemon winbind wpa_supplic +ant xfs ypbind yum-updatesd); my @ServiceCheckList = ("spray", "echo", "daytime", "discard", "charge +n", "ttdb", "ypbind", "ypserv", "yppasswdd", "ypxfrd", "tooltalk", "r +statd", "comsat", "talk", "uucp", "finger", "netstat", "systat", "rus +ers", "walld", "rexd", "rje", "netbios", "lpd", "http", "gopher", "tc +pmux", "news", "nntp", "snmp", "mail", "smtp", "pop2", "pop3", "sendm +ail", "httpd");
foreach my $service (@ServiceCheckList) { if (grep($service, @ServicesOnMachine)) { print "$service matches\n"; } }

Correction

foreach my $service (@ServiceCheckList) { if (grep(/^$service$/, @ServicesOnMachine)) { print "$service matches\n"; } }

Thanks!

Replies are listed 'Best First'.
Re^4: Comparing two arrays...
by LanX (Saint) on Apr 21, 2011 at 13:47 UTC
    your misinterpreting this test, all $services will seemingly "match", just try my @ServicesOnMachine=("nonsense").

    The first argument to grep is a boolean condition, your putting a string there which evaluates to true.

    Cheers Rolf

      I corrected the bad answers. Thanks for helping me to understand the mistake. :)