1

I need to get my code to produce the following output, but I can't get it to work.

Example program output

Please enter your 3 numbers: 12 45 78
Your numbers forward: 
12 
45 
78 
Your numbers reversed: 
78 
45 
12

My Perl code

#!/usr/bin/perl

#use strict;
use warnings;
use 5.010;

print "Please enter your 3 numbers: \n";
my $n1 = <STDIN>;
my $n2 = <STDIN>;
my $n3 = <STDIN>;

print "Your numbers forward: \n";
print $n1;
print $n2;
print $n3;

#Possible Backup Idea
# my @names = (n1, n2, n3);
# foreach my $n (@names) {
#   say $n;
# }

#2nd Possible Backup Idea
# print "$coins[0]\n"; #Prints the first element
# print "$coins[-1]\n"; #Prints the last element
# print "$coins[-2]"; #Prints 2nd to last element

print "Your numbers reversed: \n";
print $n3;
print $n2;
print $n1;

But when it runs it doesn't take the input all in one line like I need, and it must be input three times to work.

Please enter your 3 numbers: 
12
23
34
Your numbers forward: 
12
23
34
Your numbers reversed: 
34
23
12

2 Answers 2

1

You can use stdin to take the input but you'll want to split according to the space character as delimiter.

#!/usr/bin/perl
use warnings;
use strict;
use feature qw(say);

say "Pick 3 numbers";
my $input = <STDIN>;
my @numbers = split(/\s+/, $input);
my @reverse_numbers = reverse(@numbers);


say "Your numbers forward:";
say join("\n", @numbers);
say "Your numbers backwards:";
say join("\n", @reverse_numbers);
Sign up to request clarification or add additional context in comments.

Comments

1

my $n1 = <STDIN>; reads one full line at a time. So doing it three times will read three lines.

Instead, you want to read one line and split it up on whitespace into an array of numbers.

my $input = <STDIN>;
my @numbers = split /\s+/, $input;

/\s+/ is a regular expression to match any number of whitespace characters. See the Perl Regex Tutorial for more.

Then you can work with the list of numbers using for loops.

print "Your numbers forward:\n";
for my $number (@numbers) {
    print "$number\n";
}

print "Your numbers reversed: \n";
for my $number (reverse @numbers) {
    print "$number\n";
}

3 Comments

This method is fine but you're going to be a bit inefficient if the numbers went up.
@MikeTung How do you reckon? Your answer would use a lot more memory making copies and strings if the size gets large. Anyhow, the OP is just starting out; this is just the basics.
Turns out both algorithms happen in O(n) but the difference being that in my version it is much more explicit and you don't have to deal with context or for loops and you can use the say function so it'll be like print with newline.

Your Answer

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