Perl Tips

On my C Tips and Tricks page I describe a way of using colours and cursor positioning at a console using ANSI codes. These ANSI codes are not language specific, but terminal specific. So it is possible to use the same technique in Perl programs. Take a look at these subroutines:

sub gotoxy
        {
        my ($es);
        $es=sprintf("\x1B[%1dG\x1B[%1dd",$_[0], $_[1]);
        print $es;
        }

sub clear
        {
        print "\x1B[2J\x1B[0d\x1B[0G";
        }

Using colours is also easy. Simply issue a print command with the ANSI escape sequence:

print "\x1B[??m";


where ?? is the desired colour. Use the following colours:

Foreground

Background

Colour

ANSI value

Colour

ANSI value

Black

30

Black

40

Red

31

Red

41

Green

32

Green

42

Brown

33

Brown

43

Blue

34

Blue

44

Magenta

35

Magenta

45

Cyan

36

Cyan

46

White

37

White

47



Using the foreground colour Yellow is also possible: make it bright and brown. Yellow is not available as a background colour.

Speaking about bright, these attributes are also available for the text colour:

Attribute

Ansi Value

Normal

0

Bold

1

Blink

5

Reverse

7



You'll find a demonstration of these ANSI codes in my connect4 game on my Perl scripts page. The ANSI codes only work if your terminal fully support them.


Last update: august 21, 2000