in reply to Are strings lists of characters?
If you really want a lazy list, could you just use an iterator? The following will return the individual characters, but only as you need them. Further, it won't do a split, but it does reverse the string internally, so a very long string may be an issue. I just hacked it together to demonstrate one strategy. It could use some clean up.
#!/usr/bin/perl -w use strict; sub NEXT { $_[0]->() } sub string_to_char_iter { my $string = shift; $string = reverse $string; sub { '' ne $string ? chop $string : undef } } my $string = join '', 'a' .. 'z'; my $iter = string_to_char_iter $string; while ( defined ( my $char = NEXT $iter ) ) { print "$char\n"; }
Cheers,
Ovid
Update: Just in case it's not clear, this was just some demo code. Obviously, for a string of 26 characters, creating an iterator would be overkill. Iterators are going to be more useful if you have a large amount of data that is difficult to fit into memory, such as reading from a file, or if you need to keep track of where you are in your data while reading it.
Oh, and I tweaked the code just a hair.
Join the Perlmonks Setiathome Group or just click on the the link and check out our stats.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Re: Are strings lists of characters?
by John M. Dlugosz (Monsignor) on Oct 17, 2002 at 20:11 UTC | |
by Ovid (Cardinal) on Oct 17, 2002 at 20:48 UTC | |
by Chmrr (Vicar) on Oct 18, 2002 at 05:43 UTC | |
by John M. Dlugosz (Monsignor) on Oct 18, 2002 at 14:34 UTC | |
by jeffa (Bishop) on Oct 17, 2002 at 20:47 UTC | |
by John M. Dlugosz (Monsignor) on Oct 18, 2002 at 14:29 UTC | |
by Ovid (Cardinal) on Oct 18, 2002 at 17:01 UTC | |
by John M. Dlugosz (Monsignor) on Oct 18, 2002 at 20:51 UTC | |
by shotgunefx (Parson) on Oct 17, 2002 at 23:01 UTC |