Beefy Boxes and Bandwidth Generously Provided by pair Networks
go ahead... be a heretic
 
PerlMonks  

Re: removing elements in array in perl

by Corion (Patriarch)
on Nov 23, 2016 at 09:05 UTC ( [id://1176388]=note: print w/replies, xml ) Need Help??


in reply to removing elements in array in perl

What code have you written and how does it fail?

See also perlfaq4, How do I compute the intersection of two arrays?.

Replies are listed 'Best First'.
Re^2: removing elements in array in perl
by t-rex (Scribe) on Nov 23, 2016 at 09:29 UTC

    updated the question with my code, pls check it now

      Ah - I was confused about your double usage of numbers as array elements and array indices.

      To me, it feels as if you have a number $n and want to remove $n elements from @A1 and put them into A2:

      use strict; use Data::Dumper; my @A1 = qw(a b c d e f g); my $n = 2; my @A2 = splice @A1, @A1-$n, $n; print Dumper [\@A1, \@A2]; __END__ $VAR1 = [ [ 'a', 'b', 'c', 'd', 'e' ], [ 'f', 'g' ] ];

        That can be slightly simplified due to the way splice handles a negative OFFSET:

        c:\@Work\Perl\monks>perl -wMstrict -le "use Data::Dumper; ;; my @A1 = qw(a b c d e f g); my $n = 2; my @A2 = splice @A1, -$n; ;; print Dumper [\@A1, \@A2]; " $VAR1 = [ [ 'a', 'b', 'c', 'd', 'e' ], [ 'f', 'g' ] ];
        (If  $n is greater than the number of elements of the array, a run-time error is thrown.)

        Update: Actually, the negative offset approach might be significantly better because it throws an error whenever  $n is greater than the number of array elements, whereas the
            splice @A1, @A1-$n, $n
        expression produces a silent, possibly unexpected/undesirable aliasing behavior for some values of  $n > @array and doesn't throw an error until  $n is greater than twice the number of elements of the array.

        c:\@Work\Perl\monks>perl -wMstrict -le "use Data::Dump qw(dd); ;; my @A1 = qw(a b c d e f g); my $n = 14; my @A2 = splice @A1, @A1-$n, $n; ;; dd \@A1, \@A2; " ([], ["a" .. "g"]) c:\@Work\Perl\monks>perl -wMstrict -le "use Data::Dump qw(dd); ;; my @A1 = qw(a b c d e f g); my $n = 15; my @A2 = splice @A1, @A1-$n, $n; ;; dd \@A1, \@A2; " Modification of non-creatable array value attempted, subscript -8 at - +e line 1.


        Give a man a fish:  <%-{-{-{-<

        this works, great thank you

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://1176388]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others lurking in the Monastery: (7)
As of 2024-04-23 16:52 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found