in reply to Re: How do I get rid of the cr/lf
in thread How do I get rid of the cr/lf

Hi again, I'll give a code sample:
#opening the file for reading open IN,"$fileName" ; #reading the whole file into an array. my @F=<IN>; close IN; #reading the last line of the file my $lastLine=$F[$#F]; my $firstLine=$F[0]; #spliting last line by tabs my @line=split /\t/,$lastLine; #spliting first line by tabs my @firstSplitLine=split /\t/,$firstLine; #finding the column number that equals the fieldName my $fieldNum = -1; my $numberOfFields = scalar(@firstSplitLine); for($counter=0 ; $counter < $numberOfFields ; $counter++) { $ourstring = $firstSplitLine[$counter]; $ourstring =~ s/\n\n/\n/g; #=~ s/ \s//g;# HERE IS WHERE I'M TRYING + DIFFERENT STUFF... if($fieldName eq $ourstring) # The "problematic" area { $fieldNum=$counter; last; } } # if the field wasn't found if($fieldNum==-1) { print STDERR "\n" if ($permit_writing); print STDERR "The field you asked for was not found, now returning l +ast value: $lastValue\n" if ($permit_writing); print STDERR "\n" if ($permit_writing); return $lastValue; } #printing the required field print STDERR " Value: $line[$fieldNum]\n\n" if ($permit_writing); return $line[$fieldNum];

Edit: Changed <pre> tags to <code> tags (davorg)

Replies are listed 'Best First'.
Re^3: How do I get rid of the cr/lf
by davorg (Chancellor) on Aug 22, 2006 at 14:08 UTC

    (Please use <code> tags to display code, not <pre>tags)

    Do you have "use warnings" in your code? I ask because the important piece of your code seems to be if($fieldName eq $ourstring) and according to the extract you've shown us, $fieldName is undefined at that point.

    But assuming that it's set somewhere outside of this extract, I still think that you can simplify a lot of this code. I'd consider setting up a hash where the keys are the column names and the associated values are the column numbers. Something like:

    my %columns; @columns{@split_first_line} = 0 .. $#split_first_line;

    You can then get the column number associated with a given field name with a simple:

    if (defined (my $field_num = $columns{$field_name})) { # field exists }

    Also, the best place to deal with chomping the input data is probably as soon as you've read it in, when a simple chomp(@f) would suffice.

    --
    <http://dave.org.uk>

    "The first rule of Perl club is you do not talk about Perl club."
    -- Chip Salzenberg