monkeybus has asked for the wisdom of the Perl Monks concerning the following question:

Hello monks,

Suppose I have an array like

$foo[0] = "xy";

$foo[1] = "yx";

How can I read individual letters of each element to ascertain what is is?

i.e., how can I tell if the first letter is x, or y?

Thank you kindly.

Replies are listed 'Best First'.
Re: Reading parts of array elements
by GrandFather (Saint) on Dec 09, 2009 at 06:40 UTC

    Perl offers many ways to do that, depending on what you want to achieve. For example you could:

    my @subArray = grep {/^x/} @foo;

    to get all the elements that contain a string starting with x. Or you could:

    my @firstLetters = map {substr $_, 0, 1} @foo;

    to get an array of the first letter of each element in @foo. Or you could:

    my @asLetters = map {[split '']} @foo;

    to get an array of arrays of individual letters - each @asLetters element is an array of the letters in the corresponding string from @foo.

    Now, what was it you wanted?


    True laziness is hard work
Re: Reading parts of array elements
by desemondo (Hermit) on Dec 09, 2009 at 06:36 UTC
    How can I read individual letters of each element to ascertain what is is?

    and

    How can I tell if the first letter is x, or y?
    Those sound like 2 different requirements to me. One quite simple, the other slightly more complex...


    1. What are you actually aiming to do?
    2. And what does your @foo array actually contain?

    Right now, your question is just another XY Problem (pardon the pun)
Re: Reading parts of array elements
by Fox (Pilgrim) on Dec 09, 2009 at 10:51 UTC
    ord uses the first char of EXPR so:
    for(@words) { print chr ord $_; }
    would print only first letters
Re: Reading parts of array elements
by Anonymous Monk on Dec 09, 2009 at 06:28 UTC
Re: Reading parts of array elements
by pid (Monk) on Dec 09, 2009 at 07:39 UTC

    Sometimes I wonder if we could do something like $foo[0][0], $foo[1][0], etc, things might become easier.
    I always do my $first_char = (split ('', $foo[0]))[0]; when I met similar problems.

      my $first_char = substr $foo[0], 0, 1;

      is much clearer, at least to my eye, probably executes faster and is faster to type too. What you might call a 'win win win' scenario.


      True laziness is hard work

        Thanks for this, I have to say that this is much better than my way of doing it.
        Mine's more or less a bad example. :)

Re: Reading parts of array elements
by igoryonya (Pilgrim) on Dec 09, 2009 at 14:32 UTC
    I'd say, if, for example, you want to get the second char from the second array element:
    say substr($foo[1], 1, 1);
    The last substr element means that you only need 1 character from the string.