Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Using data files with only one Field

Status
Not open for further replies.

copykat

Technical User
May 25, 2006
2
US
I know how to use and maintain .txt data files with two or more fields. I want to learn how to use just one field so I can do away with the $nothing field which... does nothing. I just use it so the data file will have two fields separated with a comma (The only way I know to work it). My name.txt file consists of:
name1,
name2,
name3,
nameetc,

This is the code to read the name.txt file.
Code:
#!/usr/bin/perl -w

my ($nothing, $name, @records, $rec);

open (INFILE, "<", "name.txt");
@records = <INFILE>;
close(INFILE);
foreach $rec (@records) {
	chomp ($rec);
	($name, $nothing) = split(/,/, $rec);
print "$name <br>\n";
}
 
I think you're making this far more complicated than you need to.
Lose the trailing comma in the records.
Then a "chomped" $_ is all you need. No need to split.
From your code you could simply:
Code:
print "$_<br>\n";


Trojan.
 
Can I also suggest that you try to completely avoid statementes like this:
Code:
@records = <INFILE>;
It's begging for something to run out of memory sometime. You're coding in a timebomb by doing it.
As an example, your original code re-written safely (although not as I would do it normally) might look like this:
Code:
#!/usr/bin/perl -w

my ($nothing, $name, @records, $rec);

open (INFILE, "name.txt");
while(<INFILE>) {
    chomp;
    ($name, $nothing) = split(/,/, $_, 2);
    print "$name <br>\n";
}
close(INFILE);

As you can see, the code is actually shorter and simpler and it won't die a nasty death if your input file becomes large.

Of course, the lazy way to do what you appear to be trying to do might be something like this:
Code:
perl -lne 's/,$/<br>/;print' < 103.txt
or if you lose the trailing comma:
Code:
perl -lne 's/$/<br>/;print' < 103.txt

TIMTOWTDI



Trojan.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top