Beefy Boxes and Bandwidth Generously Provided by pair Networks
Welcome to the Monastery

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>;

Log In?

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

How do I use this? | Other CB clients
Other Users?
Others having an uproarious good time at the Monastery: (2)
As of 2023-02-04 02:59 GMT
Find Nodes?
    Voting Booth?
    I prefer not to run the latest version of Perl because:

    Results (30 votes). Check out past polls.