Beefy Boxes and Bandwidth Generously Provided by pair Networks
Think about Loose Coupling
 
PerlMonks  

substring exists at particular postion?

by redemption (Sexton)
on May 23, 2002 at 09:41 UTC ( [id://168715]=perlquestion: print w/replies, xml ) Need Help??

redemption has asked for the wisdom of the Perl Monks concerning the following question:

ok another question, this one even more newbie-ish... i took crazyinsomniac's advice and checked out the perlfaq but i couldn't find the answer... i also checked out the function listing though and it turned out the index() function but more on that later...

now what i actually want to do is to check if a particular string contains this substring at this particular position... well the index() function looks like the strpos() function in PHP (yes i'm a PHP'er :P) but i'm thinking it wouldn't really help here since i wanted to know if the substing existed only at that particular position (positions actually)... can anyone tell me how i can do this? a regexp? or is there a built-in function that would be more efficient?

thanks in advance!
  • Comment on substring exists at particular postion?

Replies are listed 'Best First'.
Re: substring exists at particular postion?
by hotshot (Prior) on May 23, 2002 at 09:48 UTC
    You can use substr function for getting the substring in the positions you want and compare it to your string:
    my $bigStr = 'Once upon a time there was a little programer'; my $littleStr = 'time'; my $neededPos = 12; my $length = 4; if (substr($bigStr, 12, $length) eq $neededStr) { &do_something; } else { &do_somthing_else; }


    Thanks.

    Hotshot
      What about this too (borrowing from hotshot's example):
      my $bigStr = 'Once upon a time there was a little programer'; my $littleStr = 'time'; if ($bigStr =~ /^(.*?)$littleStr/) { my $position = length($1); print "Found $littleStr at position $position\n"; # Do whatever depending on the position returned }
      Since you mentioned that you'd be looking for the string in more than one position, this will allow you to do the match once.
(MeowChow) Re: substring exists at particular postion?
by MeowChow (Vicar) on May 23, 2002 at 09:49 UTC
    if (substr ($str1, $pos) =~ /^\Q$str2/) { ... } # or if (substr ($str1, $pos, length $str2) eq $str2) { ... }
       MeowChow                                   
                   s aamecha.s a..a\u$&owag.print
Re: substring exists at particular postion?
by demerphq (Chancellor) on May 23, 2002 at 12:42 UTC
    Well index() will certainly do what you want. (If you have really long strings then substr() probably would be faster. But im just guessing)
    my $str="0123456Foo012345"; my $pos=7; my $srch="Foo"; print "Its there all right!" if index($str,$srch,$pos)==$pos;
    HTH

    Yves / DeMerphq
    ---
    Writing a good benchmark isnt as easy as it might look.

Re: substring exists at particular postion?
by redemption (Sexton) on May 23, 2002 at 09:59 UTC
    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!... } }
      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.
      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*


      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.

Re: substring exists at particular postion?
by hotshot (Prior) on May 23, 2002 at 10:14 UTC
    For multiple searches you can build an array of positions and using the map function construct new array of the strings found on those positions, and do what ever you like with the new array

    Thanks.

    Hotshot
      will take a look at the map function hotshot... thanks (why did you say thanks for? :-))

      yeah i realised the goof there joost... thanks for pointing that out nonetheless... so far it seems quite efficient like you say and unless someone else comes along with a faster way i guess this is it guys... thanks for all the help

      - Joel
Re: substring exists at particular postion?
by redemption (Sexton) on May 23, 2002 at 09:47 UTC
    hey i just thought maybe i could use substring() and then test if that matches... if it does, it passes the test (actually i'm going to write it to another file)... but then i'd have to do several substring()s since there are a few locations i must test and depending on which location has what, i write the line to different files... would this work? and more importantly would this be efficient, as the file is a particularly large one (more than 100 MB)...

    sorry for posting again so quickly but it struck my mind just after i'd posted...

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://168715]
Approved by rob_au
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others drinking their drinks and smoking their pipes about the Monastery: (3)
As of 2024-04-24 05:31 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found