[oak perl] Applying shift() to an array reference

Steven Kuo skuo at psi.nsc.com
Thu Sep 15 17:51:23 PDT 2005


On Thu, 15 Sep 2005, steve kolupaev wrote:

> Hi Everyone,
>
> An odd Perl question came up today on my contract job in Washington
> state.
>
> When we call the shift function on an array we get back the first
> element of the array, and the array size drops by one.
>
> When we apply the shift function to a reference to the array, the
> same thing happens.

(snipped)

>
> Members of the project from a non-Perl background find this
> surprising.  But it is consistent with the current perlref.pod
> document and matches my experience.   Nothing protects the referent
> from a properly expressed operation on its reference.



What background do your colleagues do have and what difference in
behavior were they expecting?

For example, one cannot change the size of a static array in C.  One
can mimic a shift operation using memmove and pointer dereferencing,
however.


#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void *shift (int *start, unsigned int len)
{
     int *dest = start;
     int *src = ++start;
     void *retval;
     retval = memmove(dest, src, len * sizeof *dest);
     /* shifted last defined value? */
     if (len <= 1)
 	retval = NULL;
     return retval;
}

int main (void)
{
     int array[] = { 1, 2, 3, 4 };
     int *ar;
     size_t len = (sizeof array / sizeof array[0]);
     size_t iter;
     for (ar = array, iter = 0; ar != NULL; ++iter)
     {
 	printf( "Accessed through pointer, index 0: %d\n", ar[0]   );
 	printf( "Accessed through array,   index 0: %d\n", array[0] );
 	ar = shift(ar, len--);
 	printf( "Shifting ...\n");
     }

     printf("In C, the size of a static array does not change\n");

     len = (sizeof array / sizeof array[0]);

     for (iter = 0; iter < len; ++iter)
 	printf("Garbage %d\n", array[iter]);
     return EXIT_SUCCESS;
}

__END__

Accessed through pointer, index 0: 1
Accessed through array,   index 0: 1
Shifting ...
Accessed through pointer, index 0: 2
Accessed through array,   index 0: 2
Shifting ...
Accessed through pointer, index 0: 3
Accessed through array,   index 0: 3
Shifting ...
Accessed through pointer, index 0: 4
Accessed through array,   index 0: 4
Shifting ...
In C, the size of a static array does not change
Garbage 12798104
Garbage 12798104
Garbage 12798104
Garbage 12798104


-- 
Hope this helps,
Steven




More information about the Oakland mailing list