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: Beginner:
What's wrong with that code ???

 



yaniv_av
Novice

Dec 16, 2002, 1:55 PM

Post #1 of 3 (598 views)
What's wrong with that code ??? Can't Post

@groups=(1,2,3,4);
-----------------------
I want @g1 to get (1,2) and @g2 to get (3,4).
but when I write this it won't work:
(@g1,@g2)=(@groups[0,1],@groups[2,3]);

Why ???

(This is work:
my @g1=@groups[0,1];
my @g2=@groups[2,3];)


davorg
Thaumaturge / Moderator

Dec 16, 2002, 10:56 PM

Post #2 of 3 (589 views)
Re: [yaniv_av] What's wrong with that code ??? [In reply to] Can't Post

It doesn't work because list assignment is greedy.

Your code

Code
(@g1,@g2)=(@groups[0,1],@groups[2,3]);

is exactly equivalent to

Code
(@g1,@g2)=(1,2,3,4);

or

Code
(@g1,@g2)=@groups;

There is no way for Perl to know when to stop assigning to @g1 and start assigning to @g2.

--
Dave Cross, Perl Hacker, Trainer and Writer
http://www.dave.org.uk/
Get more help at Perl Monks


uri
Thaumaturge

Dec 23, 2002, 10:36 PM

Post #3 of 3 (574 views)
Re: [yaniv_av] What's wrong with that code ??? [In reply to] Can't Post

there is a way to do that if you know how many items will go into each
array. this also will not clear out any parts of the array leftover and above the assigned slice.

Code
perl -e '(@a[0,1],@b[0,1])=2 .. 5; print "[@a] [@b]\n"' 
[2 3] [4 5]


by the proper use of arrays or expressions for the assigned indexes, it could be made more automatic.

but there is no reason not to use 2 separate assignment statements.
it is clearer and easier to understand. i wouldn't be suprised that is it faster than the above hack.

uri

 
 


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

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