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

I have to compare a line character by character including white space, How do I split up the line $variable = split (//, $_); does not work - how do I put each character in $_ into the array?
  • Comment on How Do You Parse a Line After Each Character?

Replies are listed 'Best First'.
RE: How Do You Parse a Line After Each Character?
by mikfire (Deacon) on Jul 11, 2000 at 21:57 UTC
    Hmm. First let me warn that perl doesn't like doing playing with characters like this. Second, $variable will not work - you are evaluating your split in scalar context, meaning it will return the number of characters in the line which is better done by length().
    @letters = split //;
    will work though.

    Mik Firestone ( perlus bigotus maximus )

Re: How Do You Parse a Line After Each Character?
by jjhorner (Hermit) on Jul 11, 2000 at 22:44 UTC

    From the Perl Cookbook, 1.5:

    # break into individual characters my @characters = split(//); # or if you want ASCII values my @characters = unpack("C*"); # of if you wish to use a loop while (/(.)/g) { # . is never a newline # do something with $1 }
    For a real world example, also from the Perl Cookbook (modified slightly):
    my %seen = (); my $string = "J. J. Horner is so cool!"; foreach my $byte (split //, $string) { $seen{$byte}++; } print "unique chars are: ", sort(keys %seen), "\n";

    Which yeilds: unique chars are: !.HJceilnors

    J. J. Horner
    Linux, Perl, Apache, Stronghold, Unix
    jhorner@knoxlug.org http://www.knoxlug.org/
    
RE: How Do You Parse a Line After Each Character?
by Adam (Vicar) on Jul 11, 2000 at 22:05 UTC
    Why are you comparing lines char by char? I mean, what's the purpose? Are you sorting the lines? (use cmp) Are you looking for something? (use a regular expression) I'm not sure I can think of a reason to split a string into its member chars, except maybe to scramble it, or find usage stats for various chars (also done better with a regex). Share your problem statement with us, and maybe we can cook a better solution.

    Oh, and mikfire is right about your misuse of split. It returns an array, which in scalar context is a size.