in reply to Re: Re: Are strings lists of characters?
in thread Are strings lists of characters?
Way too hackish, not to mention it breaks if the chosen delimiter appears in your input strings - I'll get back to that in a bit though.
To find the common prefix, you have to iterate over two variables; be that scalars or arrays. Using a for loop:
Or a while loop:my (@str1, @str2); my ($i, @prefix) = (0); for(@str1) { last if $_ ne $str2[$i++]; push @prefix, $_; }
I'd definitely prefer the while version, simply because the arrays are treated equally. Now let's look at how you'd do that over scalars:my (@str1, @str2); my ($i, @prefix) = (0); push @prefix, $str1[$i++] while($str1[$i] eq $str2[$i]);
my ($s1, $s2) = ("ABCD", "ABEF"); my $i = 0; $i++ while substr($s1, $i, 1) eq substr($s2, $i, 1); my $prefix = substr $s1, 0, $i;
That's hardly any different to read, way clearer than the regex solution, shorter and more idiomatic to boot, and doesn't break regardless of input. Ok, using the ternary operator for your code would shorten the regex approach, but if anything, it would probably conceil the code's intent even further.
No, the only advantage strings-as-arrays would offer as far as I can see is for simulatenously replacing multiple non-contiguous parts of the string with parts of some other string. But then, that's such a rare circumstance that it shouldn't be unacceptably painful to just listify the strings using /(.)/sg for that, then glue the result back together.
I do see compelling reasons to syntactically extend push, shift and friends for dealing with strings (although I also see reasons not to), but definitely not for making strings fullblown arrays.
Makeshifts last the longest.
|
|---|