develooper Front page | perl.perl6.language | Postings from April 2005

Re: Question about list context for String.chars

Thread Previous | Thread Next
From:
Rod Adams
Date:
April 11, 2005 20:58
Subject:
Re: Question about list context for String.chars
Message ID:
425B4740.5030809@rodadams.net
gcomnz wrote:

>Hi all, 
>
>I'm writing a bunch of examples for perl 6 pleac and it seems rather
>natural to expect $string.chars to return a list of unicode chars in
>list context, however I can't find anything to confirm that. (The
>other alternatives being split and unpack.)
>
># unpack
>@array = unpack("C*", $string);
># split
>@array = split /./, $string;
># this too?
>@array = $string.split(/./)
># and how about this?
>@array = $string.chars
># and this explicit list context?
>@array = $string.chars[];
>
>Thanks,
>
>Marcus
>
>  
>
Well, in general the word "chars" has come to mean whatever a character 
is in the current lexical scope, typically a language level char.

It had previously been decided that C<.chars>,etc would return the 
length. I'm not about to change that without approval from @Larry.

I don't see any technical problem with saying that C<.chars> returns an 
array of those chars, when then gets converted to length of array in 
scalar context. The "creating a list just to get length" can of course 
be optimized away.

My main issue is that it's it giving two rather different semantics to 
the same method name, and leaving it to what amounts to context based 
dispatching. So I don't like this idea as written.

However, I do like the idea of treating a string as an array of chars. I 
remember some discussion a while back about making [] on strings do 
something useful (but not the same thing as C<substr>), but I forget how 
it ended, and my brain is too fried to go hunt it down. But overall I 
like that idea. Then you could just say:

    @array = $string[];

Which is a lot prettier than anything you mentioned above, let's us get 
rid of the .split:/<null>/ issue, has better huffman coding, and lets 
.chars have only one meaning.

For reference, what I'm thinking of having [] do is return the chars 
specified as a list. This should be lvaluable, so you can hack at 
individual chars to your heart's content.

This is different from substr(), since the latter returns a string of 
the range of chars, not the individual chars. Consider:

    $a = $b = "All good boys go to heaven.";
    substr($a,9,3) = "girl";
    $b[9..11] = "girl"[];
    say "A: $a";
    say "B: $b";

    A: All good girls go to heaven.
    B: All good girs go to heaven.

-- Rod Adams
   

Thread Previous | Thread Next


nntp.perl.org: Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at ask@perl.org | Group listing | About