Trihedralguy has asked for the wisdom of the Perl Monks concerning the following question:

my @letters = split (/,/, $contact); my $i = 3; foreach $i (0..$#letters-1) { print "Flag $i is $letters[$i]"; }
I was in the chat this morning trying to figure this out. But i'm still having problems. Basically I have a string $contact that is formated with letter,letter,letter. It will always be the same letters (P,F,T) I took that and split it up into a list and eventually I would like to check each tag to see if its set. But for now, i'm just trying to pull the information out of the list. The example element I'm trying has: "P,F," as contact. I was wondering if someone could show me the way in what I'm doing wrong and how I can do this correctly?

Replies are listed 'Best First'.
Re: Variable into list
by Corion (Patriarch) on Jan 03, 2008 at 17:15 UTC

    Your iteration through the list is wrong, while your list gets set up correctly:

    print "Letters are >>@letters<<\n";

    will show you what letters you got from $contact.

    To iterate through the letters you got, either do:

    foreach my $letter (@letters) { print "Got letter '$letter'\n"; };

    or do

    for my $i (0..$#letters) { print "Flag $i is $letters[$i]\n"; };

    ... but no mixture of the two. Either you iterate through the array or you iterate through the indices of the array.

Re: Variable into list
by McDarren (Abbot) on Jan 03, 2008 at 17:22 UTC
    As was suggested by Corion at the time, you are probably better off with a hash for this.

    Here is a self-contained example that demonstrates:

    #!/usr/bin/perl -l use strict; use warnings; my $string = 'P,F,'; my %letters = map { $_ => 1 } split /,/, $string; for (qw(P F T)) { print "$_ is ", $letters{$_} ? "set" : "not set"; }
    Which prints:
    P is set F is set T is not set

    Cheers,
    Darren :)

Re: Variable into list
by Trihedralguy (Pilgrim) on Jan 04, 2008 at 16:22 UTC
    Thanks for you're help guys, i have a greater understanding of how this stuff works now.