Beefy Boxes and Bandwidth Generously Provided by pair Networks
XP is just a number
 
PerlMonks  

Simplify code in Perl with "unless" condition

by Chaoui05 (Scribe)
on May 27, 2016 at 15:29 UTC ( [id://1164319]=perlquestion: print w/replies, xml ) Need Help??

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

Hi Monks of Monastery ! I did this following code to compare some screenshots between differents browsers. I use Selenium::Screenshot. But i find that it's too heavy. I use the condition "unless" which is not very handy i think, and it's the first time i use it. My code here :
unless ($screen{'firefox'}->compare($screen{'chrome'})) { my $diff_file = $screen{'firefox'}->difference($screen{'chrome'}); print '#The images are not the same; see ' . $diff_file . ' for de +tails'. "\n"; `$diff_file`; unless ($screen{'internet explorer'}->compare($screen{'firefox'})) { my $diff_file = $screen{'internet explorer'}->difference($screen{' +firefox'}); print '#The images are not the same; see ' . $diff_file . ' for de +tails'. "\n"; `$diff_file`; unless ($screen{'chrome'}->compare($screen{'internet explorer'})) { my $diff_file = $screen{'chrome'}->difference($screen{'internet ex +plorer'}); print '#The images are not the same; see ' . $diff_file . ' for de +tails'. "\n"; `$diff_file`;
I have a newbie question also. I just would like to know how is it possible to simplify my code with "unless"?

Regards !

Lost in translation

Replies are listed 'Best First'.
Re: Simplify code in Perl with "unless" loop
by hippo (Bishop) on May 27, 2016 at 15:38 UTC

    There's a lot of repitition there as you can doubtless see. This suggests a loop. Here's an outline:

    #!/usr/bin/env perl use strict; use warnings; my @things = qw/firefox chrome exploder/; while (my $this = shift @things) { for my $that (@things) { print "Now compare $this with $that\n"; } last if $#things < 1; }

    You can obviously replace the print statement with whatever block you require for each permutation of entries in @things. HTH.

      Thanks. I will try to find a better solution. And yes , i can doubtless see it..obviously. And what does it mean HTH ?
      Lost in translation

        Hope This Helps


        Give a man a fish:  <%-{-{-{-<

Re: Simplify code in Perl with "unless" loop
by Corion (Patriarch) on May 27, 2016 at 15:39 UTC

    When you say you "find it's too heavy", what makes you think this?

    Where in your code is a loop and what do you want to remove?

    Note that you can always replace unless(...) by if( not ... ).

    Personally, I have the impression that it is not you who finds that code "too heavy" but your teacher or supervisor. Maybe you should go to them and ask them more about what they don't like with your code. Maybe they suggested that you replace the three unless statements with a loop.

    If you want to use a loop, I suggest you first print out the three statements and mark with a text marker in one colour the things that are identical between the three statements and then with a text marker of a different colour the things that are different between the three statements. Then you ideally review your course material on loops and find out how you can use a loop to go over the things that are the same and apply the things that need to change for each statement.

      Hello Corion. First i haven't got teacher , no longer i mean. Yes it's just a mistake. Obviously, a condition
      Lost in translation
Re: Simplify code in Perl with "unless" conditionnal
by choroba (Cardinal) on May 27, 2016 at 15:45 UTC
    We usually don't call the block that unless introduces a "loop", as it isn't repeated.

    You can use loops to iterate over the browsers, though, and you can use variables to avoid fetching the hash values every time:

    my @browsers = ('firefox', 'chrome', 'internet explorer'); for my $b1_idx (0 .. $#browsers - 1) { my $b1 = $screen{ $browsers[$b1_idx] }; for my $b2_idx ($b1_idx + 1 .. $#browsers) { my $b2 = $screen{ $browsers[$b2_idx] }; unless ($b1->compare($b2)) { my $diff_file = $b1->difference($b2); print "#The images are not the same; see $diff_file for de +tails\n"; qx{ $diff_file }; } } }

    Update: missing +1 added.

    ($q=q:Sq=~/;[c](.)(.)/;chr(-||-|5+lengthSq)`"S|oS2"`map{chr |+ord }map{substrSq`S_+|`|}3E|-|`7**2-3:)=~y+S|`+$1,++print+eval$q,q,a,
      I meaned a condition choroba Loop is a good solution. I must continue to dig which approach could be the best. Thanks
      Lost in translation
      I try to use your approach. I would like now to get an random element from the list . I did this :
      use List::Util qw(shuffle); my @random_array = shuffle(@browsers); for my $b1_idx (0 .. $#random_array - 1)
      But it seems to not work. Is it correct or is there an other way to do it ? Thanks in advance !
      Lost in translation

        What do you mean by "it seems to not work"?

        You can help us improve the quality of the answers we're giving by answering the following questions directly in your first post:

        What is the exact code you are running? Please show the exact code. This code should be self-sufficient and be shorter than 20 lines.

        What is the exact input you are giving? Please show the exact input you are giving to the above program.

        What is the output you expect? Please describe the output you expect.

        What is the exact output you get? Please show the exact output together with the complete error message(s) that Perl returns you.

        Why are you using List::Util? Have you read perlfaq or run perldoc -q random ? This will show you the many frequently asked questions (and their answers) pertaining to getting a random element of an array.

      Ok for the update
      Lost in translation
Re: Simplify code in Perl with "unless" loop
by Anonymous Monk on May 27, 2016 at 15:36 UTC

    unless (...) is the equivalent of if (not (...)) - it only simplifies your code if it makes it more readable. For example, you might find next LINE unless format_is_ok($line); more readable than next LINE if !format_is_ok($line);. When in doubt, stick with if. Also, unless is a conditional statement like if, not a "loop".

      unless (...) is the equivalent of if (not (...))

      yes this is obviously true, but can be error prone in the case of complex conditions.

      De_Morgan's_laws are useful in this case to do the correct translation between the plain and the negated form of a (possibly comlpex) condition.

      I was suggested to investigate such laws when i had an Untillian Headache

      L*

      There are no rules, there are no thumbs..
      Reinvent the wheel, then learn The Wheel; may be one day you reinvent one of THE WHEELS.
      Oh yes ! I did a big mistake. INdeed, it's a conditionnal and not a loop..end of week Thanks , i changed it in my post edit
      Lost in translation
        When you update your post: use strike tags and then put in correction. If you change the question mid-stream, posts to the original question are confusing. Make this update explicit.

        And yes "unless" is just the "NOT of if". These are all the "same".

        #!/usr/bin/perl use strict; use warnings; my $x = 5; print "x not 3\n" unless $x==3; print "x not 3\n" if $x!=3; print "x not 3\n" if !($x==3);
        Usually the "if version" is more clear. However in the above, since $x is seldom exactly 3, "unless" focuses on the usual action with Perl's ability to put the "action" first and the conditional last. For longer blocks, most often use some form of "if".

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://1164319]
Approved by Corion
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others meditating upon the Monastery: (3)
As of 2024-04-26 01:07 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found