linux poison RSS
linux poison Email

Perl Script: Input Line/record Separator examples

The input line/record separator ($/) is set to newline by default. Works like awk's RS variable, including treating blank lines as delimiters if set to the null string. You may set it to a multi-character string to match a multi-character delimiter, or can be set to the numeric value.

Below is simple perl script which demonstrate the usage of input record separator, feel free to copy and use this script.

Input File: cat testfile.txt
google:yahoo:microsoft:apple:oracle:hp:dell:toshiba:sun:redhat

Source: cat separator.pl
#!/usr/bin/perl

$FILE = "testfile.txt";
open (INFILE, $FILE) or die ("Not able to open the file");
$/ = ":";
while ($record = <INFILE>) {
        print "$record \n";
}

print "----------------------------------\n";
# Read entire file into string.

$FILE = "/etc/motd";
open (INFILE, $FILE) or die ("Not able to open the file: $FILE");
$/ = undef;
$filedata = <INFILE>;
print "$filedata \n";

print "----------------------------------- \n";
# Read the fixed length record/data (bytes) from a file.

$FILE = "testfile.txt";
open (INFILE, $FILE) or die ("Not able to open the file");
$/ = \10;
while ($filedata = <INFILE>) {
        print "$filedata \n";
}

Output: perl separator.pl
google:
yahoo:
microsoft:
apple:
oracle:
hp:
dell:
toshiba:
sun:
redhat

----------------------------------
Welcome to Ubuntu 12.04 LTS (GNU/Linux 3.2.5-gg987 x86_64)

 * Documentation:  https://help.ubuntu.com/

-----------------------------------
google:yah
oo:microso
ft:apple:o
racle:hp:d
ell:toshib
a:sun:redh
at




0 comments:

Post a Comment

Related Posts with Thumbnails