Hi everyone..
I am trying to write a perl code which appends a text file after taking two inputs from the user. It saves the file in tab delimited format. I have the input text file attached here. Now I want the file to check if the user given input is already present only in the first column of the text file. If it is present, then it doesn't append anything in the file. Otherwise it should append it.
Below is my code which is just comparing..not appending!
print "Please write your name and address below\n";
$input=<STDIN>;
$input1=<STDIN>;
chomp $input;
chomp $input1;
open FILE, "C:/Software/new1.txt" or die $!;
while (<FILE>) {
chomp;
($user)=split("\s");
if ($input=~/$user/) {
print "User name already exists.\n";
#close (FILE);
}
else {
#open FILE, ">>C:/Software/new1.txt" or die $!;
print FILE "$input\t$input1";
}
}
close (FILE);
exit;
The Tie::File module lets you treat a file like an array so you can repeatedly loop through it and push new records into it.
#!/usr/bin/perl
#tie_file.pl;
use strict;
use warnings;
use Tie::File;
my $filename = '/home/david/Programming/data/new1.txt';
tie my @array, 'Tie::File', $filename or die "Unable to Tie $filename: $!";
my ($input, $input1);
($input, $input1) = ('David', 'at home');#Try adding myself
if ( already_in_file($input) ){
print "User name already exists.\n";
}
else{
push @array, "$input\t$input1";
print "Added $input to $filename.\n"
}
sub already_in_file{
my $u2find = shift;
my $user;
foreach (@array){
($user) = split /\t/;
if ($user =~ m/$u2find/i){
return 1;#True if user already in file
}
}
return 0;#False if user not found in file
}
one more thing..I am newbie in perl so trying to learn..does return 1 always denotes true and return 0 always returns false..and is it mandatory to use them in subroutines? Also many perl books says that while can be used for multi line file looping. But in my case it did not work. Then can we say, while loop is not useful always?
thanks
one more thing..I am newbie in perl so trying to learn..does return 1 always denotes true and return 0 always returns false..and is it mandatory to use them in subroutines? Also many perl books says that while can be used for multi line file looping. But in my case it did not work. Then can we say, while loop is not useful always?
thanks
It is not mandatory for a subroutine to return 1 or 0. You could have a subroutine return any value you want.
Sure you can use a while loop to loop through a multi-line file, but in the above script you wanted to loop through and sometimes add to the file, so using Tie::File lets you treat the file like an array. I find in this case that a foreach loop is easier for looping through an array. I don't know any written rule for when to use while loops versus when to use foreach loops. Use what works and makes sense to you and is readable enough for other programmers to understand.