in reply to Array loops and assignments
Great imagination; very little attempt to use actual Perl syntax. As a wise person observed, 'you can't just make s### up and expect the computer to understand.'
If you didn't program your executable by toggling in binary, it wasn't really programming!
The use of strict and warnings would have revealed that there's far more wrong than the one syntax error you cite.
For example
- at line 1, you are trying to create an array... but you haven't declared it with "my." (Did the "myNames" nomenclature confuse you? It's a waste of effort (at least in this case) to make the var name any longer than it needs to be for clarity. It might also have made it hard for you to recognize that declaration didn't happen.)
- at line 2, you've created (and declared; ++) the $id var, BUT it is badly misnamed as it will NOT hold an id number, but rather a name; one of the elements of the array.
#!/usr/bin/perl use 5.016; use strict; use warnings; # madbeeWAG.pl -- WAG as in "It sure looks like madbee was doing wild +assed guessing." =head my @Names = ('Larry', 'Curly', 'Moe'); foreach my $id(0..$#Names) { say $id; # .... } output: C:\>madbeeWAG.pl 0 1 2 =cut my @Names = ('Larry', 'Curly', 'Moe'); my $id = 0; for my $name(@Names) { my $var = $name; my $varid = $var . $id; say $varid; ++$id; } #output 2 # Larry0 # Curly1 # Moe2 - As to breaking an array into multiple named variables, this is one (not the best, and limited but expansible) way:
#!/usr/bin/perl use 5.016; use strict; use warnings; # madbeeWAG2.pl my ($str, $list); my @Names = ('Larry', 'Curly', 'Moe'); for my $name(@Names) { $str .= ($name . ","); } (my $listitem1, my $listitem2, my $listitem3) = split /,/, $str; say "\$listitem1: $listitem1"; say "\$listitem2: $listitem2"; say "\$listitem3: $listitem3"; =head $listitem1: Larry $listitem2: Curly $listitem3: Moe =cutHowever, a little careful study of the docs on arrays will offer several more Perl-ish and more elegant approaches. Your results will vary, more of less proportionally to the effort you put into studying the docs and the standard "Learning Perl," "Intermediate Perl," ... texts.
|
---|
Replies are listed 'Best First'. | |
---|---|
Re^2: Array loops and assignments
by madbee (Acolyte) on Jul 07, 2013 at 19:39 UTC | |
by Preceptor (Deacon) on Jul 08, 2013 at 18:54 UTC |
In Section
Seekers of Perl Wisdom