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 TouchToneTommy on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Greediness in tr question 1

Status
Not open for further replies.

bigbalbossa

Programmer
Mar 21, 2002
87
US
I'm trying to count the number of delimiters in a line, but having trouble with files that are delimited by ~^. If the file is delimited by a pipe...the following code works fine, but when ~^ is introduced...tr treats each character separately. Can you make tr look for ~^ together?

#!/usr/bin/perl

#use strict;

#if( @ARGV != 2 ) {die "\nUsage: pipes_per_line.pl <filename> <# pipes per line>\n\n";}

#######################################################################


#Set autoflush to keep data out of the buffer!
$| = 1;

my %line_totals = ();
my $count = 0;
my $line = 0;
my $num_delim = $ARGV[1];

open(FILE, "$ARGV[0]") || die "Can't open file $ARGV[0]\n";
while(<FILE>) {
chomp;

#Get distinct delim count
my $delim_count = tr/~^/~^/;
$line_totals{$delim_count}++;
}
foreach my $count (keys %line_totals) {
print "There are ", $line_totals{$count}, " line(s) with $count ~^ as delimiter\n";
}

 
>>Can you make tr look for ~^ together

As far as I know the answer is no. tr works on single characters only. You can use the s/// operator though:


Code:
my $delim_count = ($_ =~ s/~\^/~\^/g);
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top