Front page | perl.beginners |
Postings from March 2002
Re: string indexing
Thread Previous
|
Thread Next
From:
John W. Krahn
Date:
March 4, 2002 12:15
Subject:
Re: string indexing
Message ID:
3C83D5E9.454302A@acm.org
Bob Ackerman wrote:
>
> I am used to indexing a string in other languages, so i would like to say
> $x="abcd";
> print $x[3];
> and see 'd' printed, but, of course, this isn't correct in perl.
>
> so i did
> @y=split(//,"abcd");
> print $y[2],"\n";
>
> and that's fine.
>
> now, how do i do that without an intermediate array.
> i want to say
> print split(//,"abcd")[1],"\n";
>
> but i get compilation error.
>
> or is there some built-in way to index a string?
You need parenthesis to get a list context for the [1] to work, so:
print( (split(//, "abcd"))[1], "\n");
Or:
print( (split //, "abcd")[1], "\n");
Or:
print +(split //, "abcd")[1], "\n";
Or:
print substr("abcd", 1, 1), "\n";
Or:
print unpack("xa", "abcd"), "\n";
John
--
use Perl;
program
fulfillment
Thread Previous
|
Thread Next