kamal
kamal

Reputation: 9785

How can i convert the following bash script into a perl script


#!/bin/bash

i="0"

echo ""
echo "##################"
echo "LAUNCHING REQUESTS"
echo "  COUNT:  $2 "
echo "  DELAY:  $3 "
echo "  SESSID: $1"
echo "##################"
echo ""

while [ $2 -gt "$i" ]
do
  i=$[$i+1]
  php avtest.php $1 $4 &
  echo "EXECUTING REQUEST $i"
  sleep $3
done

here is a better/modified script in bash


#!/bin/bash

i="0"
#startTime=`date +%s`
startTime=$(date -u +%s)
startTime=$[$startTime+$1+5]
#startTime=$($startTime+$1+5)
dTime=`date -d @$startTime`
echo ""
echo "##################"
echo "LAUNCHING REQUESTS"
echo "  COUNT:  $1 "
echo "  DELAY:  1 "
#echo "  EXECUTION:  $startTime "
echo "  The scripts will fire at :  $dTime "
echo "##################"
echo ""

while [ $1 -gt "$i" ]
do
  i=$[$i+1]
  php avtestTimed.php $1 $3 $startTime &
  echo "QUEUEING REQUEST $i"
  sleep 1
done

Upvotes: 1

Views: 1155

Answers (1)

sorpigal
sorpigal

Reputation: 26086

Here's a direct translation

#!/usr/bin/env perl
use strict;
use warnings;

print <<HERE;
##################
LAUNCHING REQUESTS
  COUNT:  $ARGV[1]
  DELAY:  $ARGV[2]
  SESSID: $ARGV[0]
##################
HERE

my $i = 0;
while($ARGV[1] > $i){
    $i += 1;
    system("php avtest.php $ARGV[0] $ARGV[3] &");
    print "EXECUTING REQUEST $i\n";
    sleep $ARGV[2];
}

But it would make more sense to read the command line parameters into variables named after what they're for and not rely on remembering argument ordering.

A brief errata in the conversion:

I use a here string to represent multiline text. I could also have put in multiple print statements to more closely mimic the bash version

In bash arguments are accessed as numbered variables, starting with $1 and going up. In Perl the argument list is represented by the array @ARGV, which is numbered starting at zero (like arrays in most languages). In both bash and Perl the name of the script can be found in the variable $0.

In Perl arrays are written as @arrayname when refering to the entire array, but they use $arrayname[index] when accessing array members. So the Perl $list[0] is like the bash ${list[0]} and the Perl @list is like the bash ${list[@]}.

In Perl variables are declared with the my keyword; the equivalent in bash would be declare.

I've used the system function for spawning background processes. Its argument can be simply the command line as you might use it in bash.

Unlike echo, print requires to be told if there should be a newline at the end of the line. For recent versions of Perl the say function exists which will append a newline for you.

The Perl sleep function is pretty self-explanatory.

EDIT: Due to a typo $i in the print statement had been represented as $ni leading to runtime errors. This has been corrected.

Upvotes: 4

Related Questions