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.
In reply to Re: Are strings lists of characters?
by Ovid
in thread Are strings lists of characters?
by John M. Dlugosz
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |