Jump to content

Recommended Posts

Posted

Lesson 3

 

What are If statements and loops?

 

Every Perl script is made of instructions which tell theinterpreter what to do. Depending on the purpose of the script you'llwrite different instructions. Sometimes, you might want someinstructions to be executed only on certain conditions. To do this,you'll use If statements. A typical If statement is aninstruction which defines three elements:

 

    *

 

      A condition

    *

 

      A set of instruction to execute if the condition is met

    *

 

      A set of instruction to execute if the condition is not met

 

For instance,consider the following code:

 

if ($time > 12){

print "Good Afternoon";

}

else {

print"Good Morning";

}

 

 

In this Ifstatement, the condition is ($time > 12). If the condition is metthen the script prints "Good afternoon", otherwise itprints "Good morning".

 

Sometimes, you might wantsome instructions to be executed more than once. For this you can useloops. A typical loop is composed of a condition and a set ofinstructions to execute. There are different kinds of loops and wewill study them in the chapters below.

 

If statements in Perl

 

Perl is a very flexible language and this is particularly truewhen it comes to If statements.

 

Simple If-statements

 

The most common form of If statement in programming is composed ofa condition (between parenthesis) followed by a set of instructionswhich are placed between brackets. For instance:

 

if ($time > 12) {

print "time is $time\n";

print"Good Afternoon\n";

}

 

 

Although it is considered bad practice, you don't have towrite the brackets if there is only one instruction in the Ifstatement:

 

if ($time > 12)

print "Good Afternoon\n";

 

To avoid any possible confusion, it is recommended to always writethe brackets, or, if there is only one simple instruction to placethe condition and the instruction on the same line:

 

if($time > 12) print "Good Afternoon\n";

 

In Perl, you can also write the condition after the instructionitself. For instance:

 

print "Good Afternoon\n" if($time > 12);

 

Else and Elsif Statements

 

Similarly, you can define an “else” block of instructions,which will be executed if the condition is not met:

 

print"time is $time\n";

if ($time > 12) {

print "GoodAfternoon\n";

}

else {

print "Good Morning\n";

}

 

Sometime you may want to dosomething depending on more than one condition. Of course you canalways define If statement within others, but you can also use elsif,as a contraction of “else, if (something else..)”:

 

if ($time < 12) {

print "GoodMorning\n";

}

elsif ($time < 20) {

print "Good Afternoon\n";

}

elsif ($time < 23) {

print "Good Evening\n";

}

else {

print "Good night\n";

}

 

Unless-statements

 

In Perl, you can use the Unlessstatement. It behaves exactly like the If statement but executes thecode if the condition is not met. For instance the following codeprints “Good night” if it's more than 11pm:

 

print "Good night\n" unless($time < 11pm);

 

Loops in Perl

 

There are many different kinds of loop in Perl. Here are the mostcommon types.

 

While loop

 

This loop executes a block of code while a condition remains true.For instance, the following code prints “Hello” three times:

 

$i = 0;

while ($i < 3) {

print "Hello\n";

$i = $i + 1;

}

 

Until loop

 

This loop executes a block of code until a condition becomes true.For instance, the following code prints “Hello” three times:

 

$i = 1;

until ($i > 3) {

print "Hello\n";

$i = $i + 1;

}

 

For loop

 

The for loop is composed of four elements:

 

    *

 

      A starting assignment

    *

 

      A condition

    *

 

      An incrementation

    *

 

      A set of instructions

 

The notation of the For-loop is as follows:

 

for (starting assignment; condition; incrementation) {

instructions

}

 

The for loop starts by executing the starting assignment. Then,while the condition is met, it keeps executing the instructions andthe incrementation. For instance the following For-loop prints“Hello” three times:

 

for ($i = 0; $i < 3; $i = $i + 1) {

print "Hello\n";

}

 

Note that the ++ operator is usually used to increment a variable,so we could have written $i++ instead of $i = $i + 1;

 

In Perl, you can also use the For-loop with a “range operator”.The notation for the range operator is “..”. For instance, thefollowing code prints “Hello” three times:

 

for (1..3) {

print "Hello\n";

}

Foreach loop

 

The foreach loop is used to iterate through the elements of anarray. For instance, the following code prints the days of the week:

 

@days = ("Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday");

foreach $dayOfTheWeek (@days) {

    print "$dayOfTheWeek\n";

}

 

You can also use the foreach loop to iterate through the keys of anhashtable. For instance, the following code prints the days of theweek:

 

%days = ();

$days{"Monday"} = 1;

$days{"Tuesday"} = 2;

$days{"Wednesday"} = 3;

$days{"Thursday"} = 4;

$days{"Friday"} = 5;

$days{"Saturday"} = 6;

$days{"Sunday"} = 7;

 

foreach $day (keys %days) {

print "$day is the day number $days{$day} of the week\n";

}

 

File Handling

 

The Perl language was designed to make file handling easy andefficient, so you'll probably won't have any problem opening filesand reading them.

 

Opening and closing files

 

In order to open a file, you'll use the “open” instructionwhich takes two arguments: the name of a filehandle and the name ofthe file itself. The filehandle is like a variable which representsthe handling of the file within the script. For instance, in thefollowing code we're opening the file “clients.txt” with afilehandle called CLIENTS:

 

open (CLIENTS, "clients.txt");

 

By default, the file is open in read-mode, which means you canonly read from it. You can decide to open a file in write-mode, inorder to be able to write into it. If the file already existed or hadsome data written into it, the data will be lost. To open a file inwrite-mode simply add a “>” in front of the file name:

 

open (CLIENTS, ">clients.txt");

 

If you'd rather keep the data written in the file, you can openthe file in append-mode. This way, the data will be kept, and whatyou'll write in the file will be appended to it. In order to do thisadd a “>>” in front of the file name:

 

open (CLIENTS, ">>clients.txt");

 

The “open” instruction returns true if it managed to open thefile, false otherwise. You can use this value in order to test thesuccess of the operation. For instance, the following code opens thefile in write-mode and prints “Insufficient privileges” if thescript doesn't manage to do so.

 

open (CLIENTS, ">clients.txt") or print "Insufficientprivileges\n";

 

Remember to always close the files once you're finished with them.If you don't your changes might be lost. In order to close a file,simply use the “close” instruction on the filehandle:

 

close (CLIENTS);

 

Writing into files

 

Once the file is open in write mode you can write into it simplyby writing into its filehandle. The “print” instruction writesthings on the screen by default, but you can specify a filehandle towrite into. For instance, the following code adds a line “Mr JohnDoe” in the end of the “clients.txt” file:

 

open (CLIENTS, ">>clients.txt") or die "Insufficientprivileges\n";

print CLIENTS "Mr John Doe\n";

close (CLIENTS);

 

Reading data from files

 

There are many ways to read the content of a file. Here are thetwo most common ways in Perl.

 

Copying the content of the file into an array

 

You can copy the whole content of the file into an array. Eachline will then correspond to an element of the array. Here is anexample:

 

open(CLIENTS, "clients.txt");

@lines = ;

close(CLIENTS);

print @lines; 

 

Looping through the filehandle

 

Alternatively you can loop through the filehandle in a while loopby writing while($line = ) (think of it as “whilethere are lines in the clients file, I'm assigning the current lineto $line):

 

open (CLIENTS, "clients.txt");

while ($line = ) {

print $line;

}

close (CLIENTS);

 

As you can see, Perl makes it very easy to manipulate files. Inthe next lesson we'll look at how to search for a particular elementwithin a file, and how to handle and manipulate strings.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
  • Posts

    • I’ve seen tools like Find Person Name by Photo come in handy for creators who want to understand their audience better or spot fake accounts trying to piggyback on their growth. Pairing something like that with a solid SMM panel can make your workflow feel way smoother, especially if you're trying to grow without getting tangled in guesswork.
    • Join our discord: https://www.lineage2.cz/discord  
    • You should buy it then I’ll make a discount  
    • Hi everyone,   In 2014, I completely stepped away from developing L2 servers and doing L2J-related work. Since then, I’ve only opened this server about once a year and helped a few servers and individuals for free. I haven’t taken on any paid L2J work since then.   LINEAGE2.GOLD is a project that has reached about Season 6. The first season launched at the end of 2020 and was a fully rebuilt Gold-style server on the Classic client (protocol 110). It featured many custom systems and enhancements. After several seasons, I decided to abandon the Mobius-based project and move to Lucera, as my goal was to get as close as possible to Interlude PTS behavior while still staying on the L2J platform.   The current project was once again completely rebuilt, this time on the Essence client (protocol 306), and is based on Lucera. Because of that, acquiring a license from Deazer is required.   My Lucera extender includes, but is not limited to: Formulas.java Basic anti-bot detection, which proved quite effective, we caught most Adrenaline users using relatively simple server-side logic, logged them, and took staff action. Simple admin account lookup commands based on IP, HWID, and similar identifiers. In-game Captcha via https://lineage2.gold/code, protected by Cloudflare, including admin commands for blacklisting based on aggression levels and whitelisting. Additional admin tools such as Auto-Play status checks, Enchanted Hero Weapon live sync, force add/remove clans from castle sieges, item listeners for live item monitoring, and more. A fully rewritten Auto-Play system with support for ExAutoPlaySetting, while still using the Auto-Play UI wheel, featuring: Debuff Efficiency Party Leader Assist Respectful Hunting Healer AI Target Mode Range Mode Summoner buff support Dwarf mechanics Reworked EffectDispelEffects to restore buffs after Cancellation. Raid Bomb item support. Reworked CronZoneSwitcher. Prime Time Raid Respawn Service. Community Board features such as Top rankings and RB/Epic status. Custom systems for Noblesse, Subclasses, support-class rewards, and much more.   Depending on the deal, the project can include: The lineage2.gold domain The website built on the Laravel PHP framework The server’s Discord Client Interface source Server files and extender source The server database (excluding private data such as emails and passwords)   I’m primarily looking for a serious team to continue the project, as it would be a shame to see this work abandoned. This is not cheap. You can DM me with offers. If you’re wondering why I’m doing this: I’ve felt a clear lack of appreciation from the L2 community, and I’m not interested in doing charity work for people who don’t deserve it. I’m simply not someone who tolerates BS. Server Info: https://lineage2.gold/info Server for test: https://lineage2.gold/download Over 110 videos YouTube playlist: https://www.youtube.com/watch?v=HO7BZaxUv2U&list=PLD9WZ0Nj-zstZaYeWxAxTKbX7ia2M_DUu&index=113
  • Topics

×
×
  • Create New...

Important Information

This community uses essential cookies to function properly. Non-essential cookies and third-party services are used only with your consent. Read our Privacy Policy and We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue..

AdBlock Extension Detected!

Our website is made possible by displaying online advertisements to our members.

Please disable AdBlock browser extension first, to be able to use our community.

I've Disabled AdBlock