here is my problem: I have 2 arrays. One is character array and represents a sliding window. Characters gets shifted from the beginning and pushed at the end. I would like to use a second array to store references to array slices that 'follow' the characters as they move along. Example:
my @char_array = ('h','e','l','l','o','w','o','r','l','d');
my $char_arr_ref=[@char_array[1..$#char_array]];
print @$char_arr_ref, "\n"; # slice contains 'elloworld';
shift(@char_array);
push(@char_array), 'x';
print @$char_arr_ref, "\n"; # slice still contains 'elloworld', not 'lloworldx' as I need;
IN other words, I would like to be able to use a second array with references to array slices (as I would do with a pointer array in C for example).
Is there an idiomatic way to do this in Perl?
UPDATE: this is part of a larger program to do fast text searches. I was going to use a hash of references (say, instead of the the 'index' function which is painfully slow. And I need to do this in Perl.
In C, your windows might be implemented using pointer arithmetic.
Except pointer arithmetic wouldn't allow you to resize the buffer (
push @char_array, 'x';
). Even in C, you'd have to use offsets.This is fortunate, because Perl doesn't have pointers, much less pointer arithmetic. But offsets? No problem!
If we're actually talking about chars, a string would be more efficient.
In fact, if we're actually talking about chars, we're quite lucky since we can use an lvalue substr and let Perl handle the offsets for us!
Way easier than C with more or less all the same benefits!
I'm not sure what you're doing, and I have my doubts about whether it is appropriate for a "fast text search" program. However, you could accomplish what you want by using a trivial subroutine instead of a reference:
Note: Why do I have my doubts? Because character arrays are rarely the right way to deal with strings in Perl. This approach is likely to be less efficient and much clunkier than using Perl's built-in string-handling facilities (especially regular expressions).
Here is an implementation using an overloaded object:
Output:
Of course, you have the overhead of a method call, but Perl simply doesn't have pointers. If you are complaining that
index
is too slow (which can't be any faster), you can only improve your algorithm, not your implementation.Update
Ikegami pointed out that
substr
might be a viable option. The following solution does not have the beauty of actually using arrays, but instead of an array of chars, we use a string. This isn't the same in Perl: strings are far more efficient.Output: