PHP ImageMagick – Resources

PHP ImageMagick – Useful Resources ”; Previous Next The following resources contain additional information on PHP ImageMagick. Please use them to get more in-depth knowledge on this. Useful Video Courses PHP Programming Online Training Most Popular 46 Lectures 9 hours Tutorialspoint More Detail PHP from Scratch Full Course 18 Lectures 1 hours Nivedita Jain More Detail Full Stack Web Development – HTML, CSS, JavaScript, PHP, ELIXIR 55 Lectures 6 hours Pranjal Srivastava, Harshit Srivastava More Detail Java, PHP and MySQL Course Bundle 53 Lectures 6 hours Harshit Srivastava More Detail Learn PHP – For Beginners 31 Lectures 1.5 hours YouAccel More Detail JavaScript, Bootstrap, and PHP – Training for Beginners 117 Lectures 5.5 hours YouAccel More Detail Print Page Previous Next Advertisements ”;

Editing TheAppearance

PHP ImageMagick – Editing TheAppearance ”; Previous Next In this chapter, you will explore how to use Imagemagick”s built-in functions to edit an image. You”ll learn how to create a faded and rounded look on the edges of your image, wrap it in a parallelogram shape, and even simulate a polaroid effect. Vignette Image The word ‘vignette’ means a small photograph or image which has a faded appearance with its background and doesn’t have a definite border. Having this effect highlights certain aspects of the image. So, to get images in this filter, Imagemagick provided an inbuilt function ‘vignetteImage()’. This function takes an image as input, applies a vignette filter, and obtained image has its borders blurred. Syntax public Imagick::vignetteImage(float $blackPoint, float $whitePoint, int $x, int $y): bool This function has 4 parameters: blackpoint, whitepoint, x, and y. ‘Blackpoint’ and ‘whitepoint’ are float values. ‘x’ is an integer value that specifies the ‘x’ offset of the ellipse and ‘y’ is an integer value that specifies the ‘y’ offset of the ellipse. Example To have a better understanding of ‘vignetteImage()’ function, look at the below example. An imagick object is created at first and an image is taken as input. Then, ‘vignetteImage’ function is applied with all the parameters specified (blackpoint=30, whitepoint=10, x=40, y=20). Finally, the output is obtained using ‘writeImage()’ function. <?php $image=new Imagick($_SERVER[”DOCUMENT_ROOT”].”/test/image.png”); $image->vignetteImage(30, 10, 40, 20); $image->writeImage($_SERVER[”DOCUMENT_ROOT”].”/test/vignetteImage.png”); ?> Assume that the following is the input image (image.png) in the program − Output Rounding corners There is a basic belief that rounded corners are easier on the eyes. That is, they are suitable for the natural movement of the head and eyes respectively. Rounding image corners can also make the image look more organized and neater. To round the corners of an image, there are an inbuilt function ‘roundCorners()’ provided by Imagemagick. This function takes an image as input, rounds the corners, and produces that image as output. Syntax public Imagick::roundCorners( float $x_rounding, float $y_rounding, float $stroke_width =10, float $displace =5, float $size_correction =-6 ): bool This function has 5 parameters: x_rounding, y_rounding, strike_width, displace, and size_correction. ‘x_rounding’ and ‘y_rounding’ are float values and they control the amount of rounding. ‘stroke_width’, ‘displace’, and ‘size-correction’ are also float values which are used to fine-tune the rounding process. Example From this example, you will be able to clearly understand the usage of this function. The image is taken as input at first by creating a new Imagick object. ‘roundCorners()’ function is applied to that image with the help of the parameters specified (x_rounding=20, y_rounding=20, stroke-width=5, displace=5, size-correction=-10). Then, the output image is obtained using the function ‘writeImage()’. <?php $image=new Imagick($_SERVER[”DOCUMENT_ROOT”].”/test/imagee.png”); $image->roundCorners(20, 20, 5, 5, -10); $image->writeImage($_SERVER[”DOCUMENT_ROOT”].”/test/roundCornerImage.png”); ?> Assume that the following is the input image (image.png) in the program − Output Polaroid Image In this chapter, you will be learning to simulate the polaroid picture. A polaroid picture is a picture that is taken by a polaroid camera. It is a type of camera that takes a picture and prints it after a few seconds. It is a type of instant print and has a special type of film holder. For simulating a polaroid image, Imagemagick has provided an inbuilt function ‘polaroidImage()’. Syntax public Imagick::polaroidImage(ImagickDraw $properties, float $angle): bool This function takes in 2 parameters: properties and angle. ‘Properties’ specifies the polaroid properties and ‘angle’ specifies the polaroid angle in float value. Example In this example, you create a new imagick object and takes an image as input. Then, apply ‘polaroidImage()’ function on that image by specifying the parameters. The polaroid image is obtained as output. <?php $image=new Imagick($_SERVER[”DOCUMENT_ROOT”].”/test/imagee.png”); $image->polaroidImage(new ImagickDraw(), 30); $image->writeImage($_SERVER[”DOCUMENT_ROOT”].”/test/polaroidImage.png”); ?> Assume that the following is the input image (image.png) in the program − Output Creation of Parallelogram In this section, you will be learning about the function ‘shearImage()’. It is an inbuilt function provided by Imagemagick. The functionality of this is to create a parallelogram. This function takes an image as input and shears the image on the X and Y axis to create a parallelogram and adds a background color. Syntax public Imagick::shearImage(mixed $background, float $x_shear, float $y_shear): bool This function takes in 3 parameters: background, x_shear, and y_shear. ‘Background’ specifies the background color, ‘x_shear’ specifies the number of degrees to shear on the X-axis, and ‘y_shear’ specifies the number of degrees to shear on the Y-axis. Example In the below example, the image is taken as input, and ‘shearImage ()’ function is applied on that image. It takes in 3 parameters (background color= rgb (100, 200, 150), x_shear=10 and y_shear=10). The obtained output is displayed using the function ‘writeImage ()’. <?php $image=new Imagick($_SERVER[”DOCUMENT_ROOT”].”/test/image.png”); $image->shearImage(”rgb(100, 200, 150)”, 10, 10); $image->writeImage($_SERVER[”DOCUMENT_ROOT”].”/test/shearImage.png”); ?> Assume that the following is the input image (image.png) in the program − Output Print Page Previous Next Advertisements ”;

Perl – Regular Expressions

Perl – Regular Expressions ”; Previous Next A regular expression is a string of characters that defines the pattern or patterns you are viewing. The syntax of regular expressions in Perl is very similar to what you will find within other regular expression.supporting programs, such as sed, grep, and awk. The basic method for applying a regular expression is to use the pattern binding operators =~ and !~. The first operator is a test and assignment operator. There are three regular expression operators within Perl. Match Regular Expression – m// Substitute Regular Expression – s/// Transliterate Regular Expression – tr/// The forward slashes in each case act as delimiters for the regular expression (regex) that you are specifying. If you are comfortable with any other delimiter, then you can use in place of forward slash. The Match Operator The match operator, m//, is used to match a string or statement to a regular expression. For example, to match the character sequence “foo” against the scalar $bar, you might use a statement like this − Live Demo #!/usr/bin/perl $bar = “This is foo and again foo”; if ($bar =~ /foo/) { print “First time is matchingn”; } else { print “First time is not matchingn”; } $bar = “foo”; if ($bar =~ /foo/) { print “Second time is matchingn”; } else { print “Second time is not matchingn”; } When above program is executed, it produces the following result − First time is matching Second time is matching The m// actually works in the same fashion as the q// operator series.you can use any combination of naturally matching characters to act as delimiters for the expression. For example, m{}, m(), and m>< are all valid. So above example can be re-written as follows − #!/usr/bin/perl $bar = “This is foo and again foo”; if ($bar =~ m[foo]) { print “First time is matchingn”; } else { print “First time is not matchingn”; } $bar = “foo”; if ($bar =~ m{foo}) { print “Second time is matchingn”; } else { print “Second time is not matchingn”; } You can omit m from m// if the delimiters are forward slashes, but for all other delimiters you must use the m prefix. Note that the entire match expression, that is the expression on the left of =~ or !~ and the match operator, returns true (in a scalar context) if the expression matches. Therefore the statement − $true = ($foo =~ m/foo/); will set $true to 1 if $foo matches the regex, or 0 if the match fails. In a list context, the match returns the contents of any grouped expressions. For example, when extracting the hours, minutes, and seconds from a time string, we can use − my ($hours, $minutes, $seconds) = ($time =~ m/(d+):(d+):(d+)/); Match Operator Modifiers The match operator supports its own set of modifiers. The /g modifier allows for global matching. The /i modifier will make the match case insensitive. Here is the complete list of modifiers Sr.No. Modifier & Description 1 i Makes the match case insensitive. 2 m Specifies that if the string has newline or carriage return characters, the ^ and $ operators will now match against a newline boundary, instead of a string boundary. 3 o Evaluates the expression only once. 4 s Allows use of . to match a newline character. 5 x Allows you to use white space in the expression for clarity. 6 g Globally finds all matches. 7 cg Allows the search to continue even after a global match fails. Matching Only Once There is also a simpler version of the match operator – the ?PATTERN? operator. This is basically identical to the m// operator except that it only matches once within the string you are searching between each call to reset. For example, you can use this to get the first and last elements within a list − Live Demo #!/usr/bin/perl @list = qw/food foosball subeo footnote terfoot canic footbrdige/; foreach (@list) { $first = $1 if /(foo.*?)/; $last = $1 if /(foo.*)/; } print “First: $first, Last: $lastn”; When above program is executed, it produces the following result − First: foo, Last: footbrdige Regular Expression Variables Regular expression variables include $, which contains whatever the last grouping match matched; $&, which contains the entire matched string; $`, which contains everything before the matched string; and $”, which contains everything after the matched string. Following code demonstrates the result − Live Demo #!/usr/bin/perl $string = “The food is in the salad bar”; $string =~ m/foo/; print “Before: $`n”; print “Matched: $&n”; print “After: $”n”; When above program is executed, it produces the following result − Before: The Matched: foo After: d is in the salad bar The Substitution Operator The substitution operator, s///, is really just an extension of the match operator that allows you to replace the text matched with some new text. The basic form of the operator is − s/PATTERN/REPLACEMENT/; The PATTERN is the regular expression for the text that we are looking for. The REPLACEMENT is a specification for the text or regular expression that we want to use to replace the found text with. For example, we can replace all occurrences of dog with cat using the following regular expression − Live Demo #/user/bin/perl $string = “The cat sat on the mat”; $string =~ s/cat/dog/; print “$stringn”; When above program is executed, it produces the following result − The dog sat on the mat Substitution Operator Modifiers Here is the list of all the modifiers used with substitution operator. Sr.No. Modifier & Description 1 i Makes the match case insensitive. 2 m Specifies that if the string has newline or carriage return characters, the ^ and $ operators will now match against a newline boundary, instead of a string boundary. 3 o Evaluates the expression only once. 4 s Allows use of . to match a newline character. 5 x Allows you to use white space in the expression for clarity. 6

Perl – Special Variables

Perl – Special Variables ”; Previous Next There are some variables which have a predefined and special meaning in Perl. They are the variables that use punctuation characters after the usual variable indicator ($, @, or %), such as $_ ( explained below ). Most of the special variables have an english like long name, e.g., Operating System Error variable $! can be written as $OS_ERROR. But if you are going to use english like names, then you would have to put one line use English; at the top of your program file. This guides the interpreter to pickup exact meaning of the variable. The most commonly used special variable is $_, which contains the default input and pattern-searching string. For example, in the following lines − Live Demo #!/usr/bin/perl foreach (”hickory”,”dickory”,”doc”) { print $_; print “n”; } When executed, this will produce the following result − hickory dickory doc Again, let”s check the same example without using $_ variable explicitly − Live Demo #!/usr/bin/perl foreach (”hickory”,”dickory”,”doc”) { print; print “n”; } When executed, this will also produce the following result − hickory dickory doc The first time the loop is executed, “hickory” is printed. The second time around, “dickory” is printed, and the third time, “doc” is printed. That”s because in each iteration of the loop, the current string is placed in $_, and is used by default by print. Here are the places where Perl will assume $_ even if you don”t specify it − Various unary functions, including functions like ord and int, as well as the all file tests (-f, -d) except for -t, which defaults to STDIN. Various list functions like print and unlink. The pattern-matching operations m//, s///, and tr/// when used without an =~ operator. The default iterator variable in a foreach loop if no other variable is supplied. The implicit iterator variable in the grep and map functions. The default place to put an input record when a line-input operation”s result is tested by itself as the sole criterion of a while test (i.e., ). Note that outside of a while test, this will not happen. Special Variable Types Based on the usage and nature of special variables, we can categorize them in the following categories − Global Scalar Special Variables. Global Array Special Variables. Global Hash Special Variables. Global Special Filehandles. Global Special Constants. Regular Expression Special Variables. Filehandle Special Variables. Global Scalar Special Variables Here is the list of all the scalar special variables. We have listed corresponding english like names along with the symbolic names. $_ The default input and pattern-searching space. $ARG $. The current input line number of the last filehandle that was read. An explicit close on the filehandle resets the line number. $NR $/ The input record separator; newline by default. If set to the null string, it treats blank lines as delimiters. $RS $, The output field separator for the print operator. $OFS $ The output record separator for the print operator. $ORS $” Like “$,” except that it applies to list values interpolated into a double-quoted string (or similar interpreted string). Default is a space. $LIST_SEPARATOR $; The subscript separator for multidimensional array emulation. Default is “34”. $SUBSCRIPT_SEPARATOR $^L What a format outputs to perform a formfeed. Default is “f”. $FORMAT_FORMFEED $: The current set of characters after which a string may be broken to fill continuation fields (starting with ^) in a format. Default is “n””. $FORMAT_LINE_BREAK_CHARACTERS $^A The current value of the write accumulator for format lines. $ACCUMULATOR $# Contains the output format for printed numbers (deprecated). $OFMT $? The status returned by the last pipe close, backtick (“) command, or system operator. $CHILD_ERROR $! If used in a numeric context, yields the current value of the errno variable, identifying the last system call error. If used in a string context, yields the corresponding system error string. $OS_ERROR or $ERRNO $@ The Perl syntax error message from the last eval command. $EVAL_ERROR $$ The pid of the Perl process running this script. $PROCESS_ID or $PID $< The real user ID (uid) of this process. $REAL_USER_ID or $UID $> The effective user ID of this process. $EFFECTIVE_USER_ID or $EUID $( The real group ID (gid) of this process. $REAL_GROUP_ID or $GID $) The effective gid of this process. $EFFECTIVE_GROUP_ID or $EGID $0 Contains the name of the file containing the Perl script being executed. $PROGRAM_NAME $[ The index of the first element in an array and of the first character in a substring. Default is 0. $] Returns the version plus patchlevel divided by 1000. $PERL_VERSION $^D The current value of the debugging flags. $DEBUGGING $^E Extended error message on some platforms. $EXTENDED_OS_ERROR $^F The maximum system file descriptor, ordinarily 2. $SYSTEM_FD_MAX $^H Contains internal compiler hints enabled by certain pragmatic modules. $^I The current value of the inplace-edit extension. Use undef to disable inplace editing. $INPLACE_EDIT $^M The contents of $M can be used as an emergency memory pool in case Perl dies with an out-of-memory error. Use of $M requires a special compilation of Perl. See the INSTALL document for more information. $^O Contains the name of the operating system that the current Perl binary was compiled for. $OSNAME $^P The internal flag that the debugger clears so that it doesn”t debug itself. $PERLDB $^T The time at which the script began running, in seconds since the epoch. $BASETIME $^W The current value of the warning switch, either true or false. $WARNING $^X The name that the Perl binary itself was executed as. $EXECUTABLE_NAME $ARGV Contains the name of the current file when reading from <ARGV>. Global Array Special Variables @ARGV The array containing the command-line arguments intended for the script. @INC The array containing the list of places to look for Perl scripts to be evaluated by the do, require, or use constructs. @F The array into which the input lines are split when the -a command-line switch is given. Global Hash Special Variables %INC

PHP ImageMagick – Introduction

PHP ImageMagick – Introduction ”; Previous Next We know that images are an easy way to improve the user experience of any website. Many experiments proved that our brain could interpret images much quicker than text. They also help in attracting attention and triggering emotions. When it comes to presenting important information, images can be of great value. How can we create or edit images dynamically, making them suitable for web applications? ”ImageMagick” does that! What is ImageMagick? ImageMagick is a freely available robust collection of tools and libraries to perform many operations on digital images. It is a software suite to read, create, edit, compose, convert, and write images in a variety of formats. These formats include DPX, EXR, GIF, JPG, JPEG, PNG, TIFF, etc. (over 200 formats). These operations are available from the command line, or C, C++, Perl, Java, PHP, or Python programming languages. In this tutorial, we will be learning about ImageMagick in PHP. What is PHP? PHP stands for Hypertext pre-processor. It is a server-side scripting language that is embedded in HTML. It contains various built-in functions which allow for fast development. These scripts are executed on the server and the software is free to download and use. What is ImageMagick in PHP? ImageMagick in PHP is a native extension that does all the operations on images. Operations also include resizing, flipping, mirroring, rotating, distorting, transforming images, adjusting image colors, or even drawing text, lines, polygons, ellipses, and curves. It is free software delivered as a ready-to-run binary distribution or as source code that you may use, copy, modify, and distribute in both open and proprietary applications. It utilizes multiple computational threads to increase performance and can read, process, or write mega-, giga-, or tera-pixel image sizes. It runs on Linux, Windows, Mac OS X, iOS, Android OS, and others. Installation and Configuring As we know that PHP is a server-side scripting language, using any web servers like Apache, Nginx, etc. to run PHP scripts would be preferable. This allows you to run the PHP scripts from your browser. There is also another way to execute the PHP scripts which is using the command line. This doesn’t require any web server to be installed. In this tutorial, you will be learning to implement ImageMagick features using the Apache server. For this, we install XAMPP. XAMPP stands for cross-platform, Apache, Maria DB, PHP, Perl. It is a free and open-source cross-platform web server solution stack package developed by Apache Friends, consisting mainly of the Apache HTTP server, Maria DB, and interpreters for scripts written in PHP and Perl programming languages. Installing XAMPP: In this section, you will be able to learn the step-by-step process of installing XAMPP. Step 1 − Open this website − https://www.apachefriends.org Step 2 − Install the latest version of XAMPP available there which is suitable for your operating system (Windows/Linux/IOS). Step 3 − The file downloaded will be something like ”xampp-windows-x64-7.4.27-2-VC15-installer’. Step 4 − Run the downloaded file. You get some warning, click ”OK”. Step 5 − The below screen appears, click ”Next”. Step 6 − Select Apache, MySQL, PHP, and phpMyAdmin. and click ”Next”. Step 7 − In this step, select any specific folder, or else, you can leave it as it is(default). Click ”Next”. Step 8 − In the next step, the files will be unpacked automatically. After the process completes, click ”Next”. Step 9 − After it completes 100%, click ”Next”. Step 10 − Now, there appears a dialog box which contains ”Completing the XAMPP setup wizard”, then click ”Finish”. Installing ImageMagick In this section, you will learn to install the ImageMagick extension and installer in PHP. Step 1 − Open the website https://mlocati.github.io Step 2 − Download both the ImageMagick extension and installer according to your PHP configuration, architecture, and thread-safety of your XAMPP version. Downloaded installer file will be in the form ”ImageMagick-7.1.0-18-vc15-x64.zip” Downloaded ImageMagick extension is in the form ”php-imagick-3.7.0-7.4-ts-vc15-x64.zip”. Step 3 − Extract all the files from the extension file downloaded (from (b)). And from those files, copy the ‘php_imagemagick.dll’ file. Step 4 − Paste the file into the ‘ext’ directory of your PHP installation. Step 5 − Extract all files from the installer file downloaded (from (a)). From that, copy all files starting with CORE_DL / IM_MOP_RL/FILTER which are DLL files. The files start from ‘CORE_RL_bzlib_.dll’ as shown in the below image. Choose the files until where they end with ‘IM_MOD_RL_yuv_.dll’. Step 6 − Paste those files to the PHP root directory where there is ”php.exe”. Step 7 − Now, go to XAMPP Control Panel. Stop Apache. Step 8 − Click ”Config” and select PHP (php.ini) file. Step 9 − In that file, find ”extensions” in that code. After ”extension=php_ftp.dll” line, type ”extension=php_imagick.dll”. Save the file. Step 10 − Restart Apache. Step 11 − Installation completed. Verification Before directly jumping to the execution part, let us first check whether Imagemagick is properly installed in PHP on your system. For this, follow the below steps. Step 1 − Go to the browser and click ”localhost”. Step 2 − Go to ”phpinfo” which is in the top right corner. Step 3 − Search for Imagick. The screen must appear as shown below. Step 4 − If it appears, the Imagick setup is successfully done. This package contains the Imagick module version, Imagick classes, release dates, and all the supported formats. Print Page Previous Next Advertisements ”;

Securing The Images

PHP ImageMagick – Securing The Images ”; Previous Next In this chapter, you will be learning to secure the images so that only the sender and the intended receiver get to see the images on the web pages. PHP Imagemagick provides image processing and manipulation, allowing you to protect your images from theft or unauthorized use. Now, we will discuss the features of PHP Imagemagick and how they can help you keep your images safe. Enciphering an Image The inbuilt function named ‘encipherImage()’ in Imagemagick, helps in enciphering the images. Converting the plain pixels image to the enciphered pixels is the process that happens in this function. The enciphered image can be viewed only by the viewer who can decipher the image using the key is given (‘passphrase’). Syntax public Imagick::encipherImage(string $passphrase): bool This function takes one parameter ‘passphrase’ which acts as a key to encrypt and decrypt images. It takes an image as input and enciphers the image using the passphrase and produces the enciphered image as output. Example In the below example, the implementation of ‘encipherImage()’ function is shown. Firstly, a new imagick object must be created and an image is taken as input. ‘Passphrase’ is defined which is a string that is passed as a parameter. Then, ‘encipherImage()’ function is applied with the help of the passphrase and the enciphered image is obtained as output. <?php $image=new Imagick($_SERVER[”DOCUMENT_ROOT”].”/test/image.jpeg”); $passphrase=”Tutorials Point”; $image->encipherImage($passphrase); $image->writeImage($_SERVER[”DOCUMENT_ROOT”].”/test/encipherImage.png”); ?> Assume that the following is the input image (image.jpeg) in the program − Output Deciphering the Image Imagemagick has provided an inbuilt function ‘decipherImage()’ which helps to decipher the image. The process of converting the encrypted image to a plain image is called deciphering an image. This function takes the enciphered image as input, converts that image to a plain image using the passphrase, and produces the plain image as output. Syntax public Imagick::decipherImage(string $passphrase): bool This function takes the ‘passphrase’ as a parameter. It helps to decipher the image. Example The following example shows how to implement the ”decipherImage()” function. To begin, create a new Imagick object and pass an image as input. You will also need to define a passphrase string which is passed as a parameter. Finally, use the ”decipherImage()” function with your passphrase to obtain a deciphered image as output. <?php $image=new Imagick($_SERVER[”DOCUMENT_ROOT”].”/test/encipherImage.png”); $passphrase=”Tutorials Point”; $image->decipherImage($passphrase); $image->writeImage($_SERVER[”DOCUMENT_ROOT”].”/test/decipherImage.png”); ?> Assume that the following is the input image (encipherImage.png) in the program − Output Print Page Previous Next Advertisements ”;

Perl – Discussion

Discuss Perl ”; Previous Next Perl is a programming language developed by Larry Wall, especially designed for text processing. It stands for Practical Extraction and Report Language. It runs on a variety of platforms, such as Windows, Mac OS, and the various versions of UNIX. This tutorial provides a complete understanding on Perl. Please enable JavaScript to view the comments powered by Disqus. Print Page Previous Next Advertisements ”;

Perl – IF…ELSE

Perl Conditional Statements – IF…ELSE ”; Previous Next Perl conditional statements helps in the decision making, which require that the programmer specifies one or more conditions to be evaluated or tested by the program, along with a statement or statements to be executed if the condition is determined to be true, and optionally, other statements to be executed if the condition is determined to be false. Following is the general from of a typical decision making structure found in most of the programming languages − The number 0, the strings ”0” and “” , the empty list () , and undef are all false in a boolean context and all other values are true. Negation of a true value by ! or not returns a special false value. Perl programming language provides the following types of conditional statements. Sr.No. Statement & Description 1 if statement An if statement consists of a boolean expression followed by one or more statements. 2 if…else statement An if statement can be followed by an optional else statement. 3 if…elsif…else statement An if statement can be followed by an optional elsif statement and then by an optional else statement. 4 unless statement An unless statement consists of a boolean expression followed by one or more statements. 5 unless…else statement An unless statement can be followed by an optional else statement. 6 unless…elsif..else statement An unless statement can be followed by an optional elsif statement and then by an optional else statement. 7 switch statement With the latest versions of Perl, you can make use of the switch statement. which allows a simple way of comparing a variable value against various conditions. The ? : Operator Let”s check the conditional operator ? :which can be used to replace if…else statements. It has the following general form − Exp1 ? Exp2 : Exp3; Where Exp1, Exp2, and Exp3 are expressions. Notice the use and placement of the colon. The value of a ? expression is determined like this: Exp1 is evaluated. If it is true, then Exp2 is evaluated and becomes the value of the entire ? expression. If Exp1 is false, then Exp3 is evaluated and its value becomes the value of the expression. Below is a simple example making use of this operator − Live Demo #!/usr/local/bin/perl $name = “Ali”; $age = 10; $status = ($age > 60 )? “A senior citizen” : “Not a senior citizen”; print “$name is – $statusn”; This will produce the following result − Ali is – Not a senior citizen Print Page Previous Next Advertisements ”;

Perl – Directories

Perl – Directories ”; Previous Next Following are the standard functions used to play with directories. opendir DIRHANDLE, EXPR # To open a directory readdir DIRHANDLE # To read a directory rewinddir DIRHANDLE # Positioning pointer to the begining telldir DIRHANDLE # Returns current position of the dir seekdir DIRHANDLE, POS # Pointing pointer to POS inside dir closedir DIRHANDLE # Closing a directory. Display all the Files There are various ways to list down all the files available in a particular directory. First let”s use the simple way to get and list down all the files using the glob operator − #!/usr/bin/perl # Display all the files in /tmp directory. $dir = “/tmp/*”; my @files = glob( $dir ); foreach (@files ) { print $_ . “n”; } # Display all the C source files in /tmp directory. $dir = “/tmp/*.c”; @files = glob( $dir ); foreach (@files ) { print $_ . “n”; } # Display all the hidden files. $dir = “/tmp/.*”; @files = glob( $dir ); foreach (@files ) { print $_ . “n”; } # Display all the files from /tmp and /home directories. $dir = “/tmp/* /home/*”; @files = glob( $dir ); foreach (@files ) { print $_ . “n”; } Here is another example, which opens a directory and list out all the files available inside this directory. #!/usr/bin/perl opendir (DIR, ”.”) or die “Couldn”t open directory, $!”; while ($file = readdir DIR) { print “$filen”; } closedir DIR; One more example to print the list of C source files you might use is − #!/usr/bin/perl opendir(DIR, ”.”) or die “Couldn”t open directory, $!”; foreach (sort grep(/^.*.c$/,readdir(DIR))) { print “$_n”; } closedir DIR; Create new Directory You can use mkdir function to create a new directory. You will need to have the required permission to create a directory. #!/usr/bin/perl $dir = “/tmp/perl”; # This creates perl directory in /tmp directory. mkdir( $dir ) or die “Couldn”t create $dir directory, $!”; print “Directory created successfullyn”; Remove a directory You can use rmdir function to remove a directory. You will need to have the required permission to remove a directory. Additionally this directory should be empty before you try to remove it. #!/usr/bin/perl $dir = “/tmp/perl”; # This removes perl directory from /tmp directory. rmdir( $dir ) or die “Couldn”t remove $dir directory, $!”; print “Directory removed successfullyn”; Change a Directory You can use chdir function to change a directory and go to a new location. You will need to have the required permission to change a directory and go inside the new directory. #!/usr/bin/perl $dir = “/home”; # This changes perl directory and moves you inside /home directory. chdir( $dir ) or die “Couldn”t go inside $dir directory, $!”; print “Your new location is $dirn”; Print Page Previous Next Advertisements ”;

Perl – File I/O

Perl – File I/O ”; Previous Next The basics of handling files are simple: you associate a filehandle with an external entity (usually a file) and then use a variety of operators and functions within Perl to read and update the data stored within the data stream associated with the filehandle. A filehandle is a named internal Perl structure that associates a physical file with a name. All filehandles are capable of read/write access, so you can read from and update any file or device associated with a filehandle. However, when you associate a filehandle, you can specify the mode in which the filehandle is opened. Three basic file handles are – STDIN, STDOUT, and STDERR, which represent standard input, standard output and standard error devices respectively. Opening and Closing Files There are following two functions with multiple forms, which can be used to open any new or existing file in Perl. open FILEHANDLE, EXPR open FILEHANDLE sysopen FILEHANDLE, FILENAME, MODE, PERMS sysopen FILEHANDLE, FILENAME, MODE Here FILEHANDLE is the file handle returned by the open function and EXPR is the expression having file name and mode of opening the file. Open Function Following is the syntax to open file.txt in read-only mode. Here less than < sign indicates that file has to be opend in read-only mode. open(DATA, “<file.txt”); Here DATA is the file handle, which will be used to read the file. Here is the example, which will open a file and will print its content over the screen. #!/usr/bin/perl open(DATA, “<file.txt”) or die “Couldn”t open file file.txt, $!”; while(<DATA>) { print “$_”; } Following is the syntax to open file.txt in writing mode. Here less than > sign indicates that file has to be opend in the writing mode. open(DATA, “>file.txt”) or die “Couldn”t open file file.txt, $!”; This example actually truncates (empties) the file before opening it for writing, which may not be the desired effect. If you want to open a file for reading and writing, you can put a plus sign before the > or < characters. For example, to open a file for updating without truncating it − open(DATA, “+<file.txt”); or die “Couldn”t open file file.txt, $!”; To truncate the file first − open DATA, “+>file.txt” or die “Couldn”t open file file.txt, $!”; You can open a file in the append mode. In this mode, writing point will be set to the end of the file. open(DATA,”>>file.txt”) || die “Couldn”t open file file.txt, $!”; A double >> opens the file for appending, placing the file pointer at the end, so that you can immediately start appending information. However, you can”t read from it unless you also place a plus sign in front of it − open(DATA,”+>>file.txt”) || die “Couldn”t open file file.txt, $!”; Following is the table, which gives the possible values of different modes Sr.No. Entities & Definition 1 < or r Read Only Access 2 > or w Creates, Writes, and Truncates 3 >> or a Writes, Appends, and Creates 4 +< or r+ Reads and Writes 5 +> or w+ Reads, Writes, Creates, and Truncates 6 +>> or a+ Reads, Writes, Appends, and Creates Sysopen Function The sysopen function is similar to the main open function, except that it uses the system open() function, using the parameters supplied to it as the parameters for the system function − For example, to open a file for updating, emulating the +<filename format from open − sysopen(DATA, “file.txt”, O_RDWR); Or to truncate the file before updating − sysopen(DATA, “file.txt”, O_RDWR|O_TRUNC ); You can use O_CREAT to create a new file and O_WRONLY- to open file in write only mode and O_RDONLY – to open file in read only mode. The PERMS argument specifies the file permissions for the file specified, if it has to be created. By default it takes 0x666. Following is the table, which gives the possible values of MODE. Sr.No. Entities & Definition 1 O_RDWR Read and Write 2 O_RDONLY Read Only 3 O_WRONLY Write Only 4 O_CREAT Create the file 5 O_APPEND Append the file 6 O_TRUNC Truncate the file 7 O_EXCL Stops if file already exists 8 O_NONBLOCK Non-Blocking usability Close Function To close a filehandle, and therefore disassociate the filehandle from the corresponding file, you use the close function. This flushes the filehandle”s buffers and closes the system”s file descriptor. close FILEHANDLE close If no FILEHANDLE is specified, then it closes the currently selected filehandle. It returns true only if it could successfully flush the buffers and close the file. close(DATA) || die “Couldn”t close file properly”; Reading and Writing Files Once you have an open filehandle, you need to be able to read and write information. There are a number of different ways of reading and writing data into the file. The <FILEHANDL> Operator The main method of reading the information from an open filehandle is the <FILEHANDLE> operator. In a scalar context, it returns a single line from the filehandle. For example − #!/usr/bin/perl print “What is your name?n”; $name = <STDIN>; print “Hello $namen”; When you use the <FILEHANDLE> operator in a list context, it returns a list of lines from the specified filehandle. For example, to import all the lines from a file into an array − #!/usr/bin/perl open(DATA,”<import.txt”) or die “Can”t open data”; @lines = <DATA>; close(DATA); getc Function The getc function returns a single character from the specified FILEHANDLE, or STDIN if none is specified − getc FILEHANDLE getc If there was an error, or the filehandle is at end of file, then undef is returned instead. read Function The read function reads a block of information from the buffered filehandle: This function is used to read binary data from the file. read FILEHANDLE, SCALAR, LENGTH, OFFSET read FILEHANDLE, SCALAR, LENGTH The length of the data read is defined by LENGTH, and the data is placed at the start of SCALAR if no OFFSET is specified. Otherwise data is placed after OFFSET bytes in SCALAR. The function