0

When executing the attatched code, entering f returns:

Arthur Putie:923-835-8745:923-812-6789:23 Wimp Lane, Kensington, DL 38758:8/31/69:126000
Barbara Kertz:385-573-8326:385-555-8321:832 Ponce Drive, Gary, IN 83756:12/1/46:268500
Betty Boop:245-836-8357:245-876-7656:635 Cutesy Lane, Hollywood, CA 91464:6/23/23:14500
Ephram Hardy:293-259-5395:293-222-3334:235 CarltonLane, Joliet, IL 73858:8/12/20:56700

When entering l returns the same as entering f, sort based on first name.

        print "Please choose either first or last name (f/l): ";
        $type = <>;
        chomp($type);
        if ( $type == "f" ) {
            system("sort list.txt");
        } elsif ( $type == "l" ) {
            system("sort -k2 list.txt");
        } else {
            print "Choice not recognized.\n";
        }

However, if I execute the commands manually in UNIX, then the commands come out sorted as they should be, ([sort list.txt] is first name alphabatized, [sort -k2 list.txt] is last name aplphabetized).

Any ideas for why this is happening, or workarounds to fix it? I am new to perl, so I would prefer to stick to UNIX command alternatives, instead of pure perl script solutions.

1 Answer 1

5

Use the eq and not == , you are using a numerical comparison where you should be doing a string comparison.

This is a classic mistake, I often do this when in a hurry and not thinking about the scalar and what I want out of it. I tested in the shell and works fine now with that change.

Sign up to request clarification or add additional context in comments.

6 Comments

Strange, that fixed the problem. Can you help me understand why that would have had the effect it did?
@chris : Perl Operators I was not happy with my other answer, the comparison operator is described here. Glad I could help.
Sorry, when you say - in the unix shell you mean as "sort list.txt" ? the issue is the if and elsif in perl , the comparisons are converted to numerics as per the link provided. The sorts will work fine of course in the shell, for this sort of problem I'd use the shell but as a Perl learning it is great. One extra assignment, how do you detect error on the system - I know the answer but what if your system call failed :)
I do also like as part of your learning, the use of the else for fall through conditions etc. Remember though to check for errors on system calls, you could even read the file in to your perl program sort it there and then output the result as system calls can take resources on loaded systems. Not bad comments on your code just things to look out for in the future.
more importantly, use warnings! $type == "f" will generate one.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.