http://www.perlmonks.org?node_id=114886

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

I'm a newbie, and struggling to understand some basic functions here. This statement isn't working, and I don't unstand why. Is there some operation of the foreach statement that is stopping my elsif from working properly? I've provided extra whitespace for easier digestion. I'm using Win32::Registry, as I can barely understand it at this point.
foreach (@vals) { $SubKey->GetValues(\%cvalues); if ($cvalues{'Server'}[2] =~ NT-PRINT1) {print "something\n"}; elsif ($cvalues{'Server'}[2] =~ NT-PRINT2) {print "another thing\n"}; }

Replies are listed 'Best First'.
Re: If question
by suaveant (Parson) on Sep 26, 2001 at 22:10 UTC
    ummm... unless NT-PRINT1 and NT-PRINT2 are subroutines that reture qr// regexps... you need to fix your regexp calls... I will assume NT-PRINT1 and NT-PRINT2 are strings you want to match (you need to quote strings 'NT-PRINT1' or "NT-PRINT1" at the very least) but to match those strings as a regexp try the following...
    foreach (@vals) { $SubKey->GetValues(\%cvalues); if ($cvalues{'Server'}[2] =~ /NT-PRINT1/) {print "something\n"}; elsif ($cvalues{'Server'}[2] =~ /NT-PRINT2/) {print "another thing\n"}; }

                    - Ant
                    - Some of my best work - Fish Dinner

      And one more thing, too: you are iterating over @vals, but you don't seem to be doing anything with those values in your loop. So effectively what you're doing is running the loop (everything from the GetValues call through the end of the elsif) over and over with the same values. If @vals has 3 elements in it (say 'foo', 'bar', and 'baz') you're running the loop 3 times, but doing nothing with 'foo', 'bar', and 'baz'.

      "One word of warning: if you meet a bunch of Perl programmers on the bus or something, don't look them in the eye. They've been known to try to convert the young into Perl monks." - Frank Willison
Re: If question
by demerphq (Chancellor) on Sep 26, 2001 at 23:49 UTC
    The first problem is that this code is a syntax error. You couldn't even compile this could you? The reason is simple:
    if ($condition) { #code }; # <-------- semicolon is syntax error elsif ($condition) { #code }
    I dont like this indent style much because of this type of problem.(I'm a cuddeled else man myself, I don't like 'em lonely :-) Change it to:
    if ($condition) { #code } elsif ($condition) { #code }
    Of course as suaveant said you'll also have to change your regex syntax.
    foreach (@vals) { $SubKey->GetValues(\%cvalues); if ($cvalues{'Server'}[2] =~/NT-PRINT1/) { print "something\n"; } elsif ($cvalues{'Server'}[2] =~/NT-PRINT2/) { print "another thing\n"; } }
    HTH

    Yves
    --
    You are not ready to use symrefs unless you already know why they are bad. -- tadmc (CLPM)