Debian lenny version packages
[pkg-perl] / deb-src / libio-stringy-perl / io-stringy-2.110 / examples / IO_Scalar_synopsis
1 #!/usr/bin/perl
2
3 =head1 NAME
4
5 IO_Scalar_synopsis - test out IO::Scalar
6
7 =head1 SYNOPSIS
8
9     ### From our distribution's top level directory:
10     perl -I./lib examples/IO_Scalar_synopsis 
11
12 =cut
13
14 use 5.005;
15 use IO::Scalar;
16 use strict;
17
18 my $line = ('-' x 60)."\n";
19 my $somestring = "My message:\n";
20
21 ###
22 ### Perform I/O on strings, using the basic OO interface...
23 ###
24
25 ### Open a handle on a string, and append to it:
26 print $line;
27 my $SH = new IO::Scalar \$somestring;
28 $SH->print("Hello");  
29 $SH->print(", world!\nBye now!\n");  
30 print "The string is now: ", $somestring, "\n";
31
32 ### Open a handle on a string, read it line-by-line, then close it:
33 print $line;
34 $SH = new IO::Scalar \$somestring;
35 while (defined($_ = $SH->getline)) { 
36     print "Got line: $_";
37 }
38 $SH->close;
39
40 ### Open a handle on a string, and slurp in all the lines:
41 print $line;
42 $SH = new IO::Scalar \$somestring;
43 print "All lines:\n", $SH->getlines; 
44
45 ### Get the current position (either of two ways):
46 my $pos = $SH->getpos;         
47 my $offset = $SH->tell;  
48
49 ### Set the current position (either of two ways):
50 $SH->setpos($pos);        
51 $SH->seek($offset, 0);
52
53 ### Open an anonymous temporary scalar:
54 print $line;
55 $SH = new IO::Scalar;
56 $SH->print("Hi there!");
57 print "I printed: ", ${$SH->sref}, "\n";      ### get at value
58
59
60
61
62 ### Don't like OO for your I/O?  No problem.  
63 ### Thanks to the magic of an invisible tie(), the following now 
64 ### works out of the box, just as it does with IO::Handle:
65    
66 ### Open a handle on a string, and append to it:
67 print $line;
68 $SH = new IO::Scalar \$somestring;
69 print $SH "Hello";    
70 print $SH ", world!\nBye now!\n";
71 print "The string is now: ", $somestring, "\n";
72
73 ### Open a handle on a string, read it line-by-line, then close it:
74 print $line;
75 $SH = new IO::Scalar \$somestring;
76 while (<$SH>) {
77     print "Got line: $_";
78 }
79 close $SH;
80
81 ### Open a handle on a string, and slurp in all the lines:
82 print $line;
83 $SH = new IO::Scalar \$somestring;
84 print "All lines:\n", <$SH>;
85
86 ### Get the current position (WARNING: requires 5.6):
87 $offset = tell $SH;
88
89 ### Set the current position (WARNING: requires 5.6):
90 seek $SH, $offset, 0;
91
92 ### Open an anonymous temporary scalar:
93 print $line;
94 $SH = new IO::Scalar;
95 print $SH "Hi there!";
96 print "I printed: ", ${$SH->sref}, "\n";      ### get at value
97
98
99
100
101
102 ### Stringification:
103 print $line;
104 my $str = "";
105 $SH = new IO::Scalar \$str;
106 print $SH "Hello, ";
107 print $SH "world!";
108 print "I printed: $SH\n";
109
110
111 ### Done!
112 1;