home news blogs forums events research newsletter whitepapers careers


Network Computing Network Computing Network Computing
HOT PICKS

IMMERSE YOURSELF:

SOA

  |

Data Center

  |

802.11n

  |

Data Privacy

  |
APO  |

Virtualization

  |

NAC

  |

Security

  |

Network Mgmt

  |

Enterprise Apps

  |

Storage & Servers





Beginning PERL

July 24, 2000

Brought to you by:



This manuscript is an abridged version of a chapter from the Wrox Press book Beginning PERL.

Our expert, Simon Cozens, will enlighten you with our latest network design manual chapter, "Beginning Perl." See how to handle files, directories, data and more.


Table of contents:

How It Works

This is a technique you'll often see in programming to detect when a variable has changed. $current is meant to contain the current value of $ARGV. But if it doesn't, $ARGV has changed:

   if ($current ne $ARGV) {

so we set $current to what it should be - the new value - so we can catch it again next time:

      $current = $ARGV;

We then print out the name of the new file, offset by new lines and tabs:

      print "\n\t\tFile: $ARGV\n\n";

and reset the counter so we start counting the new file from line one again.

      $lineno=1;

   }

As with most tricks like these, it's actually really simple to code it once you've seen how it's coded. The catch is having to solve problems like these for the first time by yourself.

Reading More than One Line

Sometimes we'll want to read more than one line at once. When you use the diamond operator in a scalar context, as we've been doing so far, it'll provide you with the next line. However, in a list context, it will return all of the remaining lines. For instance, you can read in an entire file like this:

open INPUT, "somefile.dat" or die $!;

my @data;

@data = ;

This is, however, quite memory-intensive. Perl has to store every single line of the file into the array, whereas you may only want to be dealing with one or two of them. Usually, you'll want to step over a file with a while loop as before. However, for some things, an array is the easiest way of doing things. For example, how do you print the last five lines in a file?

The problem with reading a line at a time is that you don't know how much text left you've got to read. You can only tell when you run out of data, so you'd have to keep an array of the last five lines read and drop an old line when a new one comes in. You'd do it something like this:

#!/usr/bin/perl

# tail.plx

use warnings;

use strict;

open FILE, "gettysburg.txt" or die $!;

my @last5;

while () {

push @last5, $_; # Add to the end

shift @last5 if @last5 > 5; # Take from the beginning

}

print "Last five lines:\n", @last5;

And that's exactly how you'd do it if you were concerned about memory use on big files. Given a suitably primed gettysburg.txt, this is what you'd get:

>perl tail.plx

Last five lines:

- that from these honored dead we take increased devotion to that cause for

which they gave the last full measure of devotion - that we here highly resolve

that these dead shall not have died in vain, that this nation under God shall

have a new birth of freedom, and that government of the people, by the people,

for the people shall not perish from the earth.

>

However, if memory wasn't a problem, or you knew you were going to be primarily dealing with small files, this would be perfectly sufficient:

#!/usr/bin/perl

# tail2.plx

use warnings;

use strict;

open FILE, "gettysburg.txt" or die $!;

my @speech = ;

print "Last five lines:\n", @speech[-5 ... -1];

What's My Line (Separator)?

So far we've been reading in single lines - a series of characters ending in a new line. One of the other things we can do is to alter Perl's definition of what separates a line.

The special variable $/ is called the 'input record separator'. Usually, it's set to be the newline character, \n, and each 'record' is a line. We might say more correctly that reads a single record from the file. Furthermore, chomp doesn't just remove a trailing new line - it removes a trailing record separator. However, we can set this separator to whatever we want, and this will change the way Perl sees lines. So if, for instance, our data was defined in terms of paragraphs, rather than lines, we could read one paragraph at a time by changing $/.



PAGE: 1 I 2 I 3 I 4 I 5 I 6 I 7 I NEXT PAGE
 





Ready to take that job and shove it?

Function:

Keyword(s):

State:
SPONSOR
RECENT JOB POSTINGS
CAREER NEWS
Go beyond Google and get vertical. These specialized search sites will help you find the business information you need -- fast.

Ari Balogh was named to the post of chief technology officer as the companys for a "realignment" of employees.










InformationWeek U.S. IT Salary Survey 2008
Salaries for business technology professionals are falling. Here's what you need to know in order to make good hiring decisions and personal career choices. Purchase Today: $299
 
ROLLING RIGHT ALONG
Follow key Network Computing Reviews from conception to completion. This Week: Holistic APM.



Network Computing Reports Emerging Enterprise Podcast Series: Secrets to Success








TechSearch


Microsite of the Week


Powerful Information at Your Fingertips



techweb
Online Communities TechWebInformationWeekLight ReadingIntelligent EnterprisebMightyNetwork ComputingDark ReadingDigital LibraryWall Street & Technology
Byte & SwitchNo JitterInternet EvolutionLight Reading's Cable Digital NewsContentinopleUnStrungBank Systems & TechnologyAdvanced TradingInsurance & Technology
Face-to-Face Events
InteropWeb 2.0 ExpoWeb 2.0 SummitVoiceConBlack HatCSISoftwareEntrprise 2.0 ConferenceGTEC
Mobile Business Expo
InformationWeek 500 ConferenceBuy Side Trading XchangeBuy Side Trading SummitBank Executive SummitInsurance Executive SummitTelcoTVEthernet ExpoOptical Expo
Magazines  
InformationWeekWall Street & TechnologyInsurance & TechnologyBank Systems & TechnologyAdvanced TradingMSDNTechNetSmart EnterpriseThe Architecture JournalDatabase Magazine
 
Research & Analyst Services  
Heavy ReadingInformationWeek ReportsInformationWeek Analytics
 
   
   
App Infrastructure   |   Messaging & Collaboration   |   Network & Systems Mgmt   |   Network Infrastructure   |   Security  |   Storage & Servers   |   Wireless   |   Enterprise Apps
About Us  |  Contact Us  |  Site Map  |  Technology Marketing Solutions  |   Briefing Centers
Copyright © 2008  United Business Media Limited  |  Privacy Statement  |  Terms of Service  |  Your California Privacy Rights