We help IT Professionals succeed at work.

Input from stdin for perl

bmcquill
bmcquill asked
on
I'm trying to take input from STDIN and push them in to an array.  I want the input to end when the user hits enter, but I can't seem to get it working correctly.  Here is what I've tried so far:

my @numbers;

while (<>) {
    s/\s+\z//;
    last if $_ eq "";
    push @numbers, $_;
}

I seem to get a blank array, any ideas?
Comment
Watch Question

Most Valuable Expert 2014
Top Expert 2015
Commented:
What was the input from STDIN, and what made the array seem blank?

Author

Commented:
THe input was just 1,2,3,4,5
And I got back 0 when I tried to print the contents of the array.
ozo
Most Valuable Expert 2014
Top Expert 2015

Commented:
How did you try to print the contents?
Was 1,2,3,4,5 all on one line?  Were there any lines before the 1,2,3,4,5?

Author

Commented:
No lines before 1,2,3,4,5, entered all on one line.

I tried to print the array by print "@numbers\n" and print "$numbers\n" both.
ozo
Most Valuable Expert 2014
Top Expert 2015

Commented:
echo "1,2,3,4,5" | perl -e '
my @numbers;

while (<>) {
    s/\s+\z//;
    last if $_ eq "";
    push @numbers, $_;
}
print "@numbers\n"
'

Open in new window

works for me, printing
1,2,3,4,5
as one array elwment
Is this what you're looking for?
echo "1,2,3,4,5" | perl -e '
my @numbers;
while (<>) {
    push @numbers, split /\D+/;
}
print "$_\n" for @numbers
'

Open in new window

Ountputs:
1
2
3
4
5