Beefy Boxes and Bandwidth Generously Provided by pair Networks
We don't bite newbies here... much
 
PerlMonks  

Re: An efficient way to gather a common portion of several strings' beginnings

by GrandFather (Saint)
on Nov 15, 2015 at 11:34 UTC ( [id://1147723]=note: print w/replies, xml ) Need Help??


in reply to An efficient way to gather a common portion of several strings' beginnings

Assuming none of your strings contain nulls:

use strict; use warnings; my @strings = ( 'string that I need to gather the common base from: number 1 and s +ome other junk in it', 'string that I need to gather the common base from: number 2 and s +ome other junk in it', 'string that I need to gather the common base number 4 and some ot +her junk in it', 'string that I need to gather the common base from: number 3 and s +ome other junk in it', ); my $common = $strings[0]; for my $str (@strings[1 .. $#strings]) { ($common ^ $str) =~ m/^\0*/; $common = substr $str, 0, $+[0] if $+[0] < length $common; } print "'$common'";

Prints:

'string that I need to gather the common base '

The xor operator ('^') combines the strings byte by byte and generates a null for each identical byte pair. @+ contains the offsets of the ends of matches. In this case the entire match is just the ticket so we use the first entry, 0, which is effectively the length of the common base.

<Update: Fixed match issue pointed out by AnomalousMonk.

Premature optimization is the root of all job security

Replies are listed 'Best First'.
Re^2: An efficient way to gather a common portion of several strings' beginnings
by AnomalousMonk (Archbishop) on Nov 15, 2015 at 18:26 UTC
    ($common ^ $str) =~ m/^\0+/;

    Please see reply above regarding  m/^\0+/ versus  m/^\0*/ match.


    Give a man a fish:  <%-{-{-{-<

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others sharing their wisdom with the Monastery: (7)
As of 2024-03-28 12:37 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found