Home: Perl Programming Help: Beginner:
print if defined statement to file



regex2012
User

Apr 19, 2016, 9:23 AM


Views: 2089
print if defined statement to file

I am trying to print this to a file:

Code
open my $FH2, '<', '/tmp/testq.txt' or die "unable to open file 'file' for reading : $!"; 
open my $FH6, '>', '/tmp/tst.txt' or die "unable to open file 'file' for reading : $!";
my %duplicates;
while (<$FH2>) {
print if defined "$duplicates{$_},";
$duplicates{$_}++;
}

but I haven't been able to . I am not sure where to indicate the file handle in this statement to get it to print the duplicate line to /tmp/tst.txt.

Can anyone help?


(This post was edited by regex2012 on Apr 19, 2016, 9:24 AM)


BillKSmith
Veteran

Apr 19, 2016, 10:40 AM


Views: 2084
Re: [regex2012] print if defined statement to file


Code
print {$FH6} $_ if defined $duplicates{$_};


Note: The braces are not required, but they make the statement easier to read because emphasize the difference between the filehandle and the data.
Good Luck,
Bill


FishMonger
Veteran / Moderator

Apr 19, 2016, 12:01 PM


Views: 2079
Re: [BillKSmith] print if defined statement to file

It should be noted that the braces would be required if the filehandle was not a plain scalar.

# braces not requried

Code
print {$FH6} $_ if defined $duplicates{$_};


# braces are required

Code
print { $FH[6] } $_ if defined $duplicates{$_};