CGI/Perl Guide | Learning Center | Forums | Advertise | Login
Site Search: in

  Main Index MAIN
INDEX
Search Posts SEARCH
POSTS
Who's Online WHO'S
ONLINE
Log in LOG
IN

Home: Perl Programming Help: Intermediate:
Convert Scalar variable to an Array

 



john_oracle
New User

Jan 26, 2016, 11:21 PM

Post #1 of 2 (1781 views)
Convert Scalar variable to an Array Can't Post

Hi,

I have a Scalar variable my $arr = "john levin jack";

Now i need to convert this to an array with new line.

Example:-
@array(0) = john
@array(1) = levin and so on.

Any Help Appreciated.
Thanks !


(This post was edited by john_oracle on Jan 27, 2016, 1:03 AM)


Laurent_R
Veteran / Moderator

Jan 27, 2016, 2:32 AM

Post #2 of 2 (1774 views)
Re: [john_oracle] Convert Scalar variable to an Array [In reply to] Can't Post

You've got a wrong wzay of accessing array items. If you have this array:

Code
my @array = ("zero", "one", "two", "three");

Then accessing the first two elements is done this way:

Code
print $array[1]; # prints "one" 
$array[0] = "nought"; # replaces zero with nought

Note the $ sigil (not the @ sigil) used for accessing a single item within an array and the use of the square brackets.

Otherwise, to split a string into a list of elements use the split function:

Code
my @words = split / /, "john levin jack";

Now @words should contain three items: "john", "levin" and "jack".


Code
print $words[1]; # prints "levin"


 
 


Search for (options) Powered by Gossamer Forum v.1.2.0

Web Applications & Managed Hosting Powered by Gossamer Threads
Visit our Mailing List Archives