Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:
I am new to Perl (with no programming experience) so please bare with me. Problem: I am having issues making this work: Using a built-in function splice I need to remove a specified number of elements from the @_ array at once rather than the one-at-a-time that shift does
the original code was:
#!/usr/bin/perl use strict; use warnings; my @first = qw(Can unlock secret); my @second = qw(you the code?); my @mixed = interleave_words( scalar(@first), @first, @second ); print "Result: @mixed\n"; sub interleave_words { my @results; my $count = shift; foreach my $index ( 0 .. $count-1 ) { $results[$index * 2] = shift; } if ( @_ != $count ) { die "Second array not same size ($count) as the first\n"; } foreach my $index ( 0 .. $count-1 ) { $results[$index * 2 + 1] = shift; } return @results; }
I have changed the following code to meet the requirement below:
#!/usr/bin/perl use strict; use warnings; my @first = qw(Can unlock secret); my @second = qw(you the code?); my @mixed = interleave_words( scalar(@first), @first, @second ); print "Result: @mixed\n"; sub interleave_words { my @results; my $count = shift; foreach my $index ( 0 .. $count-1 ) { my @merge_list = splice (@_, 0, 2); # my @merge_list1 = splice (@merge_list, 0, 2+1); print "Result: @merge_list\n"; } if (@_!=$count) { die "Second array not same size ($count) as the first\n"; } return @results; }
but it is not working I am getting wrong output: I should be getting: Result: Can you unlock the secret code?
however I am getting: Result: Can Unlock Result: secret You Result: the Code? Second array not same size (3) as the first
Can someone help me out trying to figure out what I am doing wrong or missing out
|
---|