John M. Dlugosz has asked for the wisdom of the Perl Monks concerning the following question:

What is the correct syntax to make a slice of a dereferenced list? That is, if you can normally write @s[$x, $y] = @s[$y, $x]; and you define $r=\@s;, how do you do the same thing using $r?

—John

Replies are listed 'Best First'.
Re: Syntax for Slice of dereferenced array
by CheeseLord (Deacon) on Jul 22, 2001 at 03:58 UTC

    You can do either of the following:

    @$r[1,2] = @$r[2,1];

    Or the more explicit dereferencing way:

    @{$r}[1,2] = @{$r}[2,1];

    Either way should work.

    His Royal Cheeziness

Re: Syntax for Slice of dereferenced array
by tachyon (Chancellor) on Jul 22, 2001 at 03:59 UTC
    @s = (a..z); $ref = \@s; print @{$ref}[9,0,15,7];

    cheers

    tachyon

    s&&rsenoyhcatreve&&&s&n.+t&"$'$`$\"$\&"&ee&&y&srve&&d&&print

(MeowChow) Re: Syntax for Slice of dereferenced array
by MeowChow (Vicar) on Jul 22, 2001 at 03:59 UTC
      
    my $list = [0..10]; print @$list[3..6];

    You can also enclose the reference within braces, eg. for multidimensional structures:

      
    my @list = ([0..10]); print @{$list[0]}[3..6];

       MeowChow                                   
                   s aamecha.s a..a\u$&owag.print
Re: Syntax for Slice of dereferenced array
by John M. Dlugosz (Monsignor) on Jul 22, 2001 at 04:07 UTC
    Hmm, playing around with some simpler cases, I think part of the problem was my use of x, y, and z as hash keys. The statement:my ($x,$y,$s)= @{$self}{x,y,s}; really bamboozled the compiler, and even when I commented out the rest of the function, I got errors inside the comments! The parser was messing up everything once it started on this line.

    Even though I'm using barewords as the index of a hash, it's treating the s and y as quote-like matching operators, and all you-know-what breaks loose.

    —John

      Try
        
      ($x,$y,$s)= @{$self}{'x,y,s'};
      Unless your key is of the form /\w+/, Perl will interpret it as code returning a list of keys.

      update: <CajunMan>Confusion</CajunMan> ... didn't understand what you were trying to do - if you want trouble-free barewords, do it like so:
        
      ($x,$y,$s)= @{$self}{x=>y=>s=>};
      Of course, the form you have it in now makes more sense, unless you're obfuscating.

         MeowChow                                   
                     s aamecha.s a..a\u$&owag.print
        Huh? Isn't 'x,y,s' a single key? I'm using 'x','y','s' now.

        But, basically the bareword thing doesn't work on slices, right?