Beefy Boxes and Bandwidth Generously Provided by pair Networks
Problems? Is your data what you think it is?
 
PerlMonks  

If doesn't work

by MAS4891 (Novice)
on Jun 08, 2000 at 18:55 UTC ( #17089=perlquestion: print w/replies, xml ) Need Help??

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

Im having problems with the if statements...
For some reason they just wont work!
I know the code is right, since I tried copying and pasting,
but still...

Heres an example

if($value1==$value2){ print "Value1 and 2 are equal"; }else{ print "Value1 and 2 are not equal"; }

That is the correct way to put it right?
I think it is but for some reason it just wont work,
please help

Title edit by tye

Replies are listed 'Best First'.
Re: If
by cwest (Friar) on Jun 08, 2000 at 18:59 UTC
    Be sure,(in that example) that you are comparing numbers or, non-strings. The == operator is for comparing numbers.

    So, if $value1 = 'a string' || $value2 = 'another string' You are using the incorrect syntax, otherwise, you should be good to go.

    If you're comparing strings, try this:

    if ( $value1 eq $value2 ) {
      print "I win!\n";
    } else {
      print "I loose.\n";
    }
    
    Enjoy!
    --
    Casey
    
RE: If (kudra: eq and ==)
by kudra (Vicar) on Jun 08, 2000 at 19:00 UTC
    If $value1 and $value2 are not numbers, you will need to use eq instead of ==.
    if($value1 eq $value2) { ... } else { ... }
    A recent discussion on the topic of == and eq can be found at Mysterious the ways: == and eq.

    ctweten beat me to replying, so this post is a kind of useless duplicate.

DANGER!
by Fastolfe (Vicar) on Jun 09, 2000 at 03:01 UTC
    Please read the 'perlsec' man page.

    You are doing a very dangerous open() call, passing the argument from your HTML form 'name' parameter directly to open. Thus, I can pass an argument of "mail me@example.com </etc/passwd; cat whatever |" and no one would be the wiser. It's not hard to change this into something considerably more destructive.

    Please consider running CGI apps with the -T and -w flags, which would catch major security issues like this. The 'perlsec' man page gives more detail.

RE: If
by dempa (Friar) on Jun 08, 2000 at 19:01 UTC
    From the perlop manpage:
    Binary "==" returns true if the left argument is numerically equal to the right argument. Binary "eq" returns true if the left argument is stringwise equal to the right argument.
    What does $value1 and $value2 contain?
Re: If
by Ovid (Cardinal) on Jun 08, 2000 at 21:00 UTC
    MAS4891, I can understand your frustration. I have a question and a comment. Since you have your password in the second line of the file @file[1], what's the first line of the file for? Also, in the off chance that you missed this, do you realize that @file[0] would be the first line of your file? If that's where your password is... To solve your problem, I would probably start by printing the variables you are examining.
    # debug start print "<FONT FACE='COURIER NEW'>\n"; print "'" . $query->param('pass') . "'<BR>\n"; print "'" . @file[1] . "'<BR>\n"; print "</FONT>\n"; #debug end
    I usually wrap debug code in debug "start" and "end" tags. When I go back to clean up a large script, it's quick and easy. The first line of code above sets the font to a fixed width. This makes it easier to see a space embedded in the middle of a word. The next lines print the two passwords one above the other like so:
    'diue34Tx' 'diue34Tx'
    This makes a character by character visual analysis easier and the single quotes make it obvious if you have padded white space before or after the password (but won't reveal an unchomped newline. Maybe you should use a <PRE> tag for that. Just a thought. Hope this helps!
Re: If
by MAS4891 (Novice) on Jun 08, 2000 at 19:31 UTC

    They are strings,
    before it would always say that the 2 values were equal,
    but now it says they are always not....
    Heres my code

    #!/usr/bin/perl #<include:CGI.pm> #!/usr/bin/perl -w use CGI; my $query = new CGI; print "Content-type: text/html\n\n"; open FILE,$query->param('name'); @file= <FILE>; close FILE; if ($query->param('pass') eq @file[1]){ print qq[<HTML> <frameset cols="100%,290%"> <frame src="commands.cgi?name=]; print $query->param('name'); print qq[" name="commands"> <frame src="base.cgi?name=]; print $query->param('name'); print qq[" name="game"> </frameset> </HTML>];} else{ print qq[<HTML>Sorry, that was the wrong pass/name, please try again]; }

    What I want it to do is open a file thats named the same as
    the persons user name, then check if the passwords match,
    I tried "print @file1" just to make sure I was checking the pass
    and not something else. So Im 100% sure its checking the pass,
    but now it says the passes arent equal...

      Let's make this a little nicer:
      #!/usr/bin/perl -w use strict; # you're safer with this use CGI; my $query = new CGI; print "Content-type: text/html\n\n"; my $name = $query->param('name'); my $file; { # let's be safe here with filehandles, too local *FILE; open (FILE, $name) || error("Can't find $name: $!"); my $first_line = <FILE>; chomp ($file = <FILE>); # takshaka gets bonus points for ac +tually testing it close FILE; } if ($file eq $query->param('pass')){ # more logically phrased print qq[<HTML> <frameset cols="100%,290%"> <frame src="commands.cgi?name=$name]; print qq[" name="commands"> <frame src="base.cgi?name=$name]; print qq[" name="game"> </frameset> </HTML>]; } else { error("Sorry, that was the wrong pass/name, please try again."); } sub error { my $text = shift; print qq[<HTML>$text</HTML>]; exit; }
      There, that ought to work better. You did a couple of (syntactially valid, yes) things that could come back to haunt you, so I cleaned them up. First, you read the file in list context, into an array. If you just want the second line of it, we'll throw the first one away into a temporary variable and grab the second in another statement. That'll save reading the whole thing in if it's a potentially large file. (I don't particularly like the temporary variable throwaway thing here, but it's a good way to illustrate the point. @foo1 will give warnings with strict because it ought to be written $foo1 as it returns a scalar, not a list.)

      Notice also the chomp statement, to remove the input record separator (\n, a newline) from $file. That'll make things match successfully. Most of the other stuff just makes it work under the strict pragma. There's also a little more error checking. Be sure to do that.

      I like to wrap my open calls in blocks so I can use local on the filehandles. It doesn't matter much in small scripts, but as they have a way of growing into larger files, if you already have a filehandle named FILE active somewhere else, you'll clobber it here.

      And, yes KM, there ought to be an exit at the end of the error sub, so let's redact that in. :)

        Can't modify <HANDLE> in chomp at read line 16, near "<FILE>;"

        And if you could, $file would contain '1'; chomp ($file = <FILE>);

        Why the use of the block to open the file? Why the use of local *FILE here? Why are you making two variables instead of just @foo = <FILE>; $foo[1];? Why not:

        print qq[<HTML><frameset cols="100%,290%"> <frame src="commands.cgi?name=$name" name="commands"> <frame src="base.cgi?name=$name" name="game"> </frameset> </HTML>];
        ? Why not exit at the end of error()? Otherwise the script will continue, which would make no sense, and possibly cause other errors.

        Cheers,
        KM

      First, you should always check to make sure the open worked:

      open(FILE, $query->param('name')) or die "Can't open file";
      Actually, I would not open any file directly from user input. Others may disagree in this case, but I would validate that param('name') is something you expect, likely /^\w+$/, or something similar.
      If you had warnings turned on (which you should, -w) you would see that @file[1] is better written as $file[1]. You may want to consider putting all the HTML you are printing in a here doc, what you have is pretty hard on the eyes. As for why they do not match, you may want to chomp() the line you get from the file. If the file only contains one line, you should use this:

      open(FILE, $name) or die "Can't open $name"; $pass = <FILE>; close FILE; chomp $pass; if ($query->param('pass') eq $pass) { ...etc...

      Cheers,
      KM

Re: If
by MAS4891 (Novice) on Jun 08, 2000 at 21:55 UTC

    Im 100% sure that @file1 is the pass, I already checked that,
    and I also know that the first line is useless, this is just
    to learn a little bit about perl, I plan on making the
    actual login page a little bit different, but for now
    I need to get the if statment to work for me, it works
    for me in every language but perl (JavaScript, C, C++, ect.)...

Re: If
by omega13 (Initiate) on Jul 23, 2000 at 14:27 UTC
    Well I have had the same kinds of problems, and have spent many hours online poring over the precious few perl resources in existence, bugging my friends, and using AIM to located hundreds of people with the common interest of Computing and Technology. My problem was an 'if' statement. I was comparing numeric values with the 'eq' operator. However, when i switched '==' with 'eq', the 'if' statement ALWAYS returned false. Lucky for me, while reading this discussion I noticed the 'chomp' command, incorporated it into my script, and everything worked perfectly. Wow, this site HAS to be the best perl site on the net.
Re: If
by MAS4891 (Novice) on Jun 08, 2000 at 22:12 UTC

    I got it to work! Finally... I just made a file for the
    pass to be alone and it worked! Thanx for the help everyone

Re: If
by MAS4891 (Novice) on Jun 08, 2000 at 20:05 UTC

    Ok, I still cant get it to work... just one question though
    what does chomp do?
    Also the file has 3 lines, the name, the pass,
    and a reminder for the pass.
    Should I just make a file for the pass
    and another for the rest of the info?

      chomp VARIABLE
      chomp LIST
      chomp
      This safer version of chop removes any trailing string that corresponds to the current value of $/ (also known as $INPUT_RECORD_SEPARATOR in the English module). It returns the total number of characters removed from all its arguments. It's often used to remove the newline from the end of an input record when you're worried that the final record may be missing its newline. When in paragraph mode ($/ = ""), it removes all trailing newlines from the string. If VARIABLE is omitted, it chomps $_. Example:
      while (<>) { chomp; # avoid \n on last field @array = split(/:/); # ... }
      You can actually chomp anything that's an lvalue, including an assignment:
      chomp($cwd = `pwd`); chomp($answer = <STDIN>);
      If you chomp a list, each element is chomped, and the total number of characters removed is returned.

      (I got this from perlfunc:chomp)

      -- zdog (Zenon Zabinski)
         Go Bells!!

      It seems a bit redundant to keep the name in the first line of the file and also to have the filename be the name. You're not using the name in the file for any kind of verification and you already know what it is. If you had one password file, where all names and passwords were listed, keeping the name in the file would be useful, but as it is I don't think your first line is doing anything.

      Hi, Mas, it was just a few months ago that I was asking such questions, so I thought I would offer a little help.

      Firstly, chomp removes the newline characters from a scalar value (a string). That's not EXACTLY what it does, but it's close enough, for you, for now. (Since that's what you're probably using it for, and it will probably work.)

      You can find this information by going to http://www.perldoc.com/perl5.6/pod/perlfunc.html.

      Perl Functions are the easiest things to understand about Perl, with the exception of weird ones like map (it's cool, it's helpful, but it's weird, and I can't use it reliably yet). You probably want to get a good book on perl (generally speaking, one that's published by O'Reilly http://perl.oreilly.com/). Leaf through a few and select one that you can understand. I'm on the second chapter of Programming Perl, and I've had to read a few sections twice, but it's a good book so far.

      Something that you may find helpful (because I did, when I looked up the substr() function), is: a 1value (one-value) means the left side of the equation. So this would be an example of using the substr() function as a 1value:

      substr($str,0,1) = 'D'; #set the first char of $str to 'D'

      Lastly, please look up functions before you ask about them (I've made this mistake quite a few times), and ask questions like this in the chatterbox before you post a message about them.

      Take care,
      Dave.

      "For fate which has ordained that there shall be no friendship among the evil has also ordained that there shall ever be friendship among the good." - Plato / Socrates

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://17089]
Approved by root
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others wandering the Monastery: (3)
As of 2019-06-17 00:32 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    Is there a future for codeless software?



    Results (76 votes). Check out past polls.

    Notices?
    • (Sep 10, 2018 at 22:53 UTC) Welcome new users!