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

Printing in appropriate columns (For Ozzy)

by Tyke (Pilgrim)
on Mar 20, 2001 at 21:17 UTC ( #65746=snippet: print w/ replies, xml ) Need Help??

Description: How to write an array formatted by columns. I'll leave OzzyOsbourne to explain the why's and wherefore's of this... he asked for it.

The problem was given an array containing values from A to G, we want to print the values in the appropriate column... or at least that's what I understood the problem to be ;-)

Update: Changed @s{split //} = 1; to @s{split //} = ();. The former works in this case but is misleading and plain sloppy. It puts 1 in the 'first' value of the hash and undef in the others. Since all we need to do is to 'autovivify' the elements of the hash so that the existance check works, this is OK. However, don't imagine that it puts '1' in all the hash values. The updated version is probably clearer.

Update: Rearranged ths code to work on an array rather than a string. Same principle though.

#!perl -w
use strict;

sub print_in_columns {
  my %s;

  # Push the input array into the hash  to indicate which
  # columns are present
  @s{@_} = ();

  # Loop through the permitted values and either print
  # the value ( if it exists in the hash %s, or print 
  # an empty column if it isn't
  print exists $s{$_} ? "$_\t" : "\t" for ('A'..'G');
  print "\n";    
}

print_in_columns split // while <DATA>;

__DATA__
ABC
ADE
AFG
CDB
Comment on Printing in appropriate columns (For Ozzy)
Download Code

Back to Snippets Section

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others pondering the Monastery: (16)
As of 2014-08-22 19:05 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The best computer themed movie is:











    Results (163 votes), past polls