Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

loser

macrumors newbie
Original poster
Aug 8, 2002
19
0
I am trying to figure out a way to assign a line from <STDIN> to an array. For example, the user is prompted for a line of text and he enters something like: 'a b c d' on one line and hits enter.

I want to assign to an array such that a[0] = a, a[1] = b, a[2] = c, and a[3] = d
All I have been able to find out so far is that when you assign <STDIN> to an array, each line is an index, and the user must type control-d to end the input. This is not what I'm trying to do. I can assign the input as a string to a variable; is there a way to then use that variable and assign the pieces separated by a space to different elements of the array, sort of like you can do with '@array = qw/a b c d/; ?

Thanks in advance for any help.
 

loser

macrumors newbie
Original poster
Aug 8, 2002
19
0
Thanks for your help. That was exactly what I needed.
 

iMeowbot

macrumors G3
Aug 30, 2003
8,634
0
There is one little quirk with split the you'll want to know about. If a string happens to begin with the delimiter, the array will start with an empty element. So, to add a little robustness to the /s+/ example, you may want to first strip possible leading whitespace from your string.

perldoc -q strip.blank from the shell will give some common recipes for that.
 

hsvmoon

macrumors newbie
Jul 31, 2006
24
0
Huntsville Al
split a line

I am trying to figure out a way to assign a line from <STDIN> to an array. For example, the user is prompted for a line of text and he enters something like: 'a b c d' on one line and hits enter.

I want to assign to an array such that a[0] = a, a[1] = b, a[2] = c, and a[3] = d
All I have been able to find out so far is that when you assign <STDIN> to an array, each line is an index, and the user must type control-d to end the input. This is not what I'm trying to do. I can assign the input as a string to a variable; is there a way to then use that variable and assign the pieces separated by a space to different elements of the array, sort of like you can do with '@array = qw/a b c d/; ?

Thanks in advance for any help.

$line = <STDIN>;#read line
$line =~ s/(^\s+)|(\s+$)//g;#remove lead and trail white space
@data = split(/\s+/,$line);#split on white space into array

hope this helps.
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.