1

I tried to split one string and assign an array, and then add http at the start using unshift. But, I am not getting the desired output. What am I doing wrong here?

use strict;
my $str = 'script.spoken-tutorial.org/index.php/Perl';
my @arr = split (/\//,$str);
print "chekcing the split function:\n @arr\n";
my @newarr = unshift(@arr, 'http://');
print "printing new array: @newarr\n";

the output is:

checking the split function:
 script.spoken-tutorial.org index.php Perl
printing new array: 4

Why instead of adding http is it giving number 4 (which is array length)?

2
  • See perldoc.perl.org/functions/unshift check values of @arr Commented May 8, 2021 at 6:46
  • 1
    unshift adds an element to the front of the array in its first argument, so after its use that @arr has that new element in its beginning. More importantly: you must read perldoc pages for functions as you are learning to use them! At least scan through for basics and important stuff if some are too tough to read all and understand. Commented May 8, 2021 at 7:04

1 Answer 1

3

This is documented behaviour. From perldoc -f unshift:

unshift ARRAY,LIST

Does the opposite of a shift. Or the opposite of a push, depending on how you look at it. Prepends list to the front of the array and returns the new number of elements in the array.

See the bolded last part. This means the return value of the function unshift() is the size of the array. Which is what you did.

unshift(@arr, 'http://');   # this returns 4

What you want is to do either

my @newarr = ('http://', @arr);

Or

my @newarr = @arr;
unshift @newarr, 'http://';
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.