On Jul 9, 4:36 am, [EMAIL PROTECTED] (Amichai Teumim) wrote:

> In my deck of cards I want to replace the letter of the card with the name(
> e.g. A = Ace).
>
> So I tried to implement the following snippet into my code:
>
> while @startingdeck{
>   $_ =~ s/A/Ace/;
>   print NEW;
>
> }

> Is the location just wrong, or the code?

Now why would you ask if the code is wrong?  Could it be that you got
an error of some kind?  And might you think that the error message
might be an important clue as to what's wrong?  Why wouldn't you
include that error message in your post?

Your code is both invalid syntax and logically incorrect.  Fixing the
syntax first:
while (@startingdeck) {
   $_ =~ s/A/Ace/;
   print NEW;
}

What this code says is "While there are elements in @starting deck,
search $_ for 'A', and if found replace it with 'Ace'".

You'll note two big problems here:  1) Nothing is ever assigned to
$_.  2) There is no way for this loop to end.

There are two ways to fix this problem.  One is to directly modify the
code to address both of those issues:
while ($_ = pop @startingdeck) {
   $_ =~ s/A/Ace/;
   print NEW;
}

This code now says "Remove the last element of @startingdeck, and
assign it to $_.  If $_ now contains a defined value, execute this
loop.  Replace $_'s A with Ace, print $_ to the NEW filehandle, and
return to the top".

Of course, this contains the problem that you're destroying
@startingdeck within your loop.  You haven't said whether or not you
need that array to be intact when the loop is done, but let's assume
you do.  Then the second way to fix the problem is to use the correct
structure to begin with: a foreach loop.

foreach (@startingdeck) {
   $_ =~ s/A/Ace/;
   print NEW;
}

This code says "For each element of @startingdeck, assign that element
to $_, and execute the loop.  Stop when all elements have been
iterated through."

If you don't understand the difference between a while loop and a
foreach loop, you need to read:
perldoc perlsyn

Paul Lalli


-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/


Reply via email to