perl array from <STDIN> question

Discussion in 'Mac Programming' started by loser, Nov 4, 2006.

  1. loser macrumors newbie

    Aug 8, 2002
    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.
  2. iMeowbot macrumors G3


    Aug 30, 2003
  3. loser thread starter macrumors newbie

    Aug 8, 2002
    Thanks for your help. That was exactly what I needed.
  4. iMeowbot macrumors G3


    Aug 30, 2003
    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.
  5. hsvmoon macrumors newbie

    Jul 31, 2006
    Huntsville Al
    split a line

    $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.

Share This Page