Perl script making a pattern in variables -


#! /usr/bin/perl  use strict; use warnings; #always use these! open (myfile, '>script2.txt'); $world = 1; $top (1 .. 100) {     $left (1 .. 100) {          print myfile "\#world$world \{                 background: url(/images/1.png) 0 0 no-repeat;                 float: left;                 width: 1%;                 height: 2%;                 position: absolute;                 top: $top\%;                 left: $left\%;                 z-index: -1;                 margin-top: -10px;                 margin-left: -10px;             \}              \#world$world:hover \{                 background-position: 0 -20px;                 cursor: pointer;             \}";          $world++;     } } close (myfile); 

currently perl script generates 10000 results (100 top x 100 left) how can modify $top produces 0, 2.5, 5...100 instead of 0, 1, 2, ...100 , $left produces 0, 1.25, 2.5, ... 100 instead of 0, 1, 2, ... 100

thanks

perl's foreach loop useful in many cases, when need advanced control on increment, c-style loop right tool:

for (my $top = 0; $top <= 100; $top += 2.5) {...} 

$left should easy enough figure out.

the perlsyn manual page contains more information different styles of loops, , keywords related control.

finally, modern code tends use 3 argument form of open along lexical file handle. change open line to:

open $file, '>', 'script2.txt' or die $!; 

and replace myfile $file in rest of code. there variety of reasons this, include error checking, preventing file handle clobbering, automatic closing... search here on should provide details.


as ysth points out, avoid compound errors floats, can write way:

my $low  = 0; $high = 100; $step = 2.5;  $reps = int (($high - $low) / $step); $i (0 .. $reps) {     $top = $i * $step;     ... } 

you wrap in function:

sub range {    ($low, $high, $step) = @_;    map {$low + $_ * $step} 0 .. int (($high - $low) / $step) } 

and easy as:

for $top (range 0 => 100, +2.5) {...} 

Comments

Popular posts from this blog

c# - How to set Z index when using WPF DrawingContext? -

razor - Is this a bug in WebMatrix PageData? -

visual c++ - Using relative values in array sorting ( asm ) -