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

Hello Monks!
Can you please tell me why this script does not print anything?
$string="TOPO_DOM 1; /note=Cytoplasmic; /evidence=ECO:0000269|PubMed:2 +4744376; TOPO_DOM 25..74; /note=Extracellular; /evidence=ECO:0000269| +PubMed:24744376; TOPO_DOM 100..115; /note=Cytoplasmic; /evidence=ECO: +0000269|PubMed:24744376; TOPO_DOM 141..159; /note=Extracellular; /evi +dence=ECO:0000269|PubMed:24744376; TOPO_DOM 183..227; /note=Cytoplasm +ic; /evidence=ECO:0000269|PubMed:24744376"; @split_topodom = split(/TOPO_DOM/, $string); print $split_topodom[0];
I want to split the string into chunks using the TOPO_DOM as delimiter.

Replies are listed 'Best First'.
Re: Why is this split not doing anything?
by LanX (Saint) on Feb 22, 2023 at 13:08 UTC
    You are mistaken!

    This

    • $split_topodom[0]

    is only printing the part before the first "TOPO_DOM" which is an empty string ""

    "TOPO_DOM 1 ... ^^

    You have to inspect the full array

    • @split_topodom

    Debugger-Demo

    > perl -de0 ... DB<21> $string="TOPO_DOM 1; /note=Cytoplasmic; /evidence=ECO:0000269 +|PubMed:24744376; TOPO_DOM 25..74; /note=Extracellular;..." DB<22> x split /TOPO_DOM/, $string 0 '' 1 ' 1; /note=Cytoplasmic; /evidence=ECO:0000269|PubMed:24744376; ' 2 ' 25..74; /note=Extracellular;...' DB<23>

    Cheers Rolf
    (addicted to the 𐍀𐌴𐍂𐌻 Programming Language :)
    Wikisyntax for the Monastery

Re: Why is this split not doing anythine?
by Marshall (Canon) on Feb 22, 2023 at 19:03 UTC
    As Rolf said, you want to print the entire array, not just the blank line at the beginning. Better yet, remove blank lines and also perhaps the extra blank after the keyword?

    use strict; use warnings; my $string="TOPO_DOM 1; /note=Cytoplasmic; /evidence=ECO:0000269|PubMe +d:24744376; TOPO_DOM 25..74; /note=Extracellular; /evidence=ECO:00002 +69|PubMed:24744376; TOPO_DOM 100..115; /note=Cytoplasmic; /evidence=E +CO:0000269|PubMed:24744376; TOPO_DOM 141..159; /note=Extracellular; / +evidence=ECO:0000269|PubMed:24744376; TOPO_DOM 183..227; /note=Cytopl +asmic; /evidence=ECO:0000269|PubMed:24744376"; my @split_topodom = split(/TOPO_DOM\s*/, $string); @split_topodom = grep {/\S/}@split_topodom; # remove blank lines print join "\n",@split_topodom; __END__ 1; /note=Cytoplasmic; /evidence=ECO:0000269|PubMed:24744376; 25..74; /note=Extracellular; /evidence=ECO:0000269|PubMed:24744376; 100..115; /note=Cytoplasmic; /evidence=ECO:0000269|PubMed:24744376; 141..159; /note=Extracellular; /evidence=ECO:0000269|PubMed:24744376; 183..227; /note=Cytoplasmic; /evidence=ECO:0000269|PubMed:24744376
    Update: Of course you can combine the grep that removes blank lines into the split line.
    my @split_topodom = grep{/\S/}split(/TOPO_DOM\s*/, $string);
      Oh wow, I did not notice THAT!! I feel so stupid now :P Thank you both!