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:
Bug in Perl?

 



pdolinski
Novice

Nov 5, 2015, 1:14 PM

Post #1 of 2 (1069 views)
Bug in Perl? Can't Post

hi.
I'm trying to break out of a loop when a certain word from a hash key pool is found at the beginning of a string:


Code
my $s = "my string"; 
my $print_ln = 1;

for my $key (keys (%h))
{
($print_ln = 0) and last if (index ($s, $key) == 0) # match must occur at beginning of string
}


Why does perl issue a warning stating that this
$print_ln = 0
should become this
$print_ln == 0
when all I am trying to do is assign a value just before endiing the loop? How to override perl's smarts without rewriting the one-liner into a paragraph of code?

Thanks.
Pete


FishMonger
Veteran / Moderator

Nov 5, 2015, 1:37 PM

Post #2 of 2 (1065 views)
Re: [pdolinski] Bug in Perl? [In reply to] Can't Post

Flip the statement so that the conditional is first and use && instead of and.

Code
if (index($s, $key) == 0) { $print_ln = 0 && last }


I'd even shorten it a bit by using a regex instead of index().

Code
if ($key =~ /^$s/) { $print_ln = 0 && last }


You can also just remove the parens around the assignment and use &&.

Code
$print_ln = 0 && last if (index ($s, $key) == 0);



(This post was edited by FishMonger on Nov 5, 2015, 1:42 PM)

 
 


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

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