in reply to substring exists at particular postion?

hey great! you guys must have posted just after me heh... this place is really quick in giving replies eh? i'm liking it already

anyway, glad i was on the right track there... would this be efficient? or is there another more efficient method? i ask this because (like i mentioned in my 2nd post) the input file would be very large (> 100MB) and to filter the lines into the different files, i'd need to perform several conditional tests which i'm afraid may slow down the program... this is how my code would be like
while(<IN>) { if(substr($_, 259, 1) eq "B") { print B $_; } else if (substr($_, 259, 1) eq "T") { print T $_; } else if () { # and so on for at least 10 lines!... } }

Replies are listed 'Best First'.
Re: Re: substring exists at particular postion?
by Joost (Canon) on May 23, 2002 at 10:15 UTC
    I think that writing this out will turn out to be the most efficient method, except that you only need to get the substr once for your example:

    while(<IN>) { my $t = substr($_, 259, 1); if($t eq "B") { print B $_; } else if ($t eq "T") { print T $_; } else if () { # and so on for at least 10 lines!... } }
    -- Joost downtime n. The period during which a system is error-free and immune from user input.
Re^2: substring exists at particular postion?
by particle (Vicar) on May 23, 2002 at 12:04 UTC
    if you stick with this solution, i'd use elsif instead of else if--it's proper perl. it's already been mentioned to cache the result from substr, so i'll leave that alone.

    but i'd be inclined to use a hash rather than elseif. if you use subroutines for the work, it'll be easy to maintain your code when you need to do more than just print to a handle, because all the code's in one place. here's a fully working example:

    #!/usr/bin/perl -w use strict; $|++; sub do_something(*@) { local *HANDLE = shift; print HANDLE @_; } # set up filehandles for this example # you'll probably use open()... local *B = *STDOUT; local *T = *STDERR; my %map_char_to_handle = ( B => *B, T => *T, # etc. ); while(<DATA>) { my $test_for_handle = substr($_, 2, 1); defined $map_char_to_handle{$test_for_handle} and do_something($map_char_to_handle{$test_for_handle}, $_); } __DATA__ ABC123 CAB234 BTT456 BXC789

    ~Particle *accelerates*

Re: Re: substring exists at particular postion?
by jmcnamara (Monsignor) on May 23, 2002 at 10:19 UTC

    If you are going to match the same position more than once, as indicated by your code, then you should store the value from a single call to substr and use that in the subsequent if statements:
    while(<IN>) { my $tmp = substr($_, 259, 1); if($tmp eq "B") { print B $_; } else if ($tmp eq "T") { print T $_; } else if () { # and so on for at least 10 lines!... } }

    --
    John.