In addition to excellent points by Corion, here's a few more:
- Avoid using $a and $b as they have special meaning when using sort (see code below). In general, I'd advise using more meaningful variable names than you have here.
- The data returned by $x = <>; contains the newline entered from the keyboard, e.g. if I enter ABC then $x will contain the string "ABC\n". Not taking this into account is a common error. The chomp function removes these line terminators.
- When gathering lists of input data, store them in an array.
- When you see almost identical code repeated (like your input prompts here) there's almost always a better solution typically involving a loop.
- Putting all that together, you could rewrite your input gathering code like this:
my @keyed_data = map { print qq{Number $_: }; scalar <> } (1 .. 5);
Note there's no checking of potentially unsafe, externally entered data nor does it allow for a variable range of lines.
- In comparisons, Perl uses different operators for string and numerical data: see perlop - in particular, the sections Relational Operators and Equality Operators.
- Many of Perl's functions operate on lists; some as input (e.g. print) and some as output (e.g. sort) (That's an oversimplification!). You can combine these functions such that the output of one becomes the input to another (see code below).
- We can print the entire sorted list with just one line. Important: $a and $b are Perl's special variables not yours!
print sort { $a <=> $b } @keyed_data;
Note the output is completely unformatted except for a reliance on control characters embedded in the data - which is not good.
- Take a look at sprintf for formatting strings and printf for printing them.
- Your code could have been laid out a little better. Take a look at perlstyle. I think the code typo in your post:
if ($a > $b {$bin = $b; $b = $a; $a = $bin;
print "nThis is line 1 $a $b \n";}
might have been more easily spotted if written like:
if ($a > $b {
$bin = $b; $b = $a; $a = $bin;
print "nThis is line 1 $a $b \n";
}