fh
Sponsored Links
Sponsored Links
Secleted [ 0 ] software to compare
Results 1 - 15 of about 56
FileCache 5.8.8
FileCache is a Perl module to keep more files open than the system permits. more>>
FileCache is a Perl module to keep more files open than the system permits.
SYNOPSIS
use FileCache;
# or
use FileCache maxopen => 16;
cacheout $mode, $path;
# or
cacheout $path;
print $path @data;
$fh = cacheout $mode, $path;
# or
$fh = cacheout $path;
print $fh @data;
The cacheout function will make sure that theres a filehandle open for reading or writing available as the pathname you give it. It automatically closes and re-opens files if you exceed your systems maximum number of file descriptors, or the suggested maximum maxopen.
cacheout EXPR
The 1-argument form of cacheout will open a file for writing (>) on its first use, and appending (>>) thereafter.
Returns EXPR on success for convenience. You may neglect the return value and manipulate EXPR as the filehandle directly if you prefer.
cacheout MODE, EXPR
The 2-argument form of cacheout will use the supplied mode for the initial and subsequent openings. Most valid modes for 3-argument open are supported namely; >, +>, , |- and -|
To pass supplemental arguments to a program opened with |- or -| append them to the command string as you would system EXPR.
Returns EXPR on success for convenience. You may neglect the return value and manipulate EXPR as the filehandle directly if you prefer.
CAVEATS
While it is permissible to close a FileCache managed file, do not do so if you are calling FileCache::cacheout from a package other than which it was imported, or with another module which overrides close. If you must, use FileCache::cacheout_close.
Although FileCache can be used with piped opens (-| or |-) doing so is strongly discouraged. If FileCache finds it necessary to close and then reopen a pipe, the command at the far end of the pipe will be reexecuted - the results of performing IO on FileCached pipes is unlikely to be what you expect.
The ability to use FileCache on pipes may be removed in a future release.
FileCache does not store the current file offset if it finds it necessary to close a file. When the file is reopened, the offset will be as specified by the original open file mode. This could be construed to be a bug.
<<lessSYNOPSIS
use FileCache;
# or
use FileCache maxopen => 16;
cacheout $mode, $path;
# or
cacheout $path;
print $path @data;
$fh = cacheout $mode, $path;
# or
$fh = cacheout $path;
print $fh @data;
The cacheout function will make sure that theres a filehandle open for reading or writing available as the pathname you give it. It automatically closes and re-opens files if you exceed your systems maximum number of file descriptors, or the suggested maximum maxopen.
cacheout EXPR
The 1-argument form of cacheout will open a file for writing (>) on its first use, and appending (>>) thereafter.
Returns EXPR on success for convenience. You may neglect the return value and manipulate EXPR as the filehandle directly if you prefer.
cacheout MODE, EXPR
The 2-argument form of cacheout will use the supplied mode for the initial and subsequent openings. Most valid modes for 3-argument open are supported namely; >, +>, , |- and -|
To pass supplemental arguments to a program opened with |- or -| append them to the command string as you would system EXPR.
Returns EXPR on success for convenience. You may neglect the return value and manipulate EXPR as the filehandle directly if you prefer.
CAVEATS
While it is permissible to close a FileCache managed file, do not do so if you are calling FileCache::cacheout from a package other than which it was imported, or with another module which overrides close. If you must, use FileCache::cacheout_close.
Although FileCache can be used with piped opens (-| or |-) doing so is strongly discouraged. If FileCache finds it necessary to close and then reopen a pipe, the command at the far end of the pipe will be reexecuted - the results of performing IO on FileCached pipes is unlikely to be what you expect.
The ability to use FileCache on pipes may be removed in a future release.
FileCache does not store the current file offset if it finds it necessary to close a file. When the file is reopened, the offset will be as specified by the original open file mode. This could be construed to be a bug.
Download (12.2MB)
Added: 2007-05-15 License: Perl Artistic License Price:
893 downloads
Audio::FindChunks 0.03
Audio::FindChunks can breaks audio files into sound/silence parts. more>>
Audio::FindChunks can breaks audio files into sound/silence parts.
SYNOPSIS
use Audio::FindChunks;
# Duplicate input to output, caching RMS values to a file (as a side effect)
Audio::FindChunks->new(rms_filename => x.rms, filter => 1)->get(rms_data);
# Output human-readable info, using RMS cache file xxx.rms if present:
Audio::FindChunks->new(cache_rms => 1, filename => xxx.mp3,
stem_strip_extension => 1)->output_blocks();
# Remove start/end silence (if longer than 0.2sec):
Audio::FindChunks->new(cache_rms => 1, filename => xxx.mp3,
min_actual_silence_sec => 1e100)->split_file();
# Split a multiple-sides tape recording
Audio::FindChunks->new(filename => xxx.mp3, min_actual_silence_sec => 11
)->split_file({verbose => 1});
Audio sequence is broken into parts which contain only noise ("gaps"), and parts with usable signal ("tracks").
The following configuration settings (and defaults) are supported:
# For getting PCM flow (and if averaging data is read from cache)
frequency => 44100, # If raw_pcm or override_header_info only
bytes_per_sample => 4, # likewise
channels => 2, # likewise
sizedata => MY_INF, # likewise (how many bytes of PCM to read)
out_fh => *STDOUT, # mirror WAV/PCM to this FH if filter
# Process non-WAV data:
preprocess => {mp3 => [[qw(lame --silent --decode)], [], [-]]}, # Second contains extra args to read stdin
# RMS cache (used if valid_rms)
rms_extension => .rms, # Appended to the filestem
# Averaging to RMS info
sec_per_chunk => 0.1, # The window for taking mean square
# thresholds picking from the list of sorted 3-medians of RMS data
threshold_in_sorted_min_rel => 0, # relative position of threashold_min
threshold_in_sorted_min_sec => 1, # shifted by this amount in the list
threshold_factor_min => 1, # the list elt is multiplied by this
threshold_in_sorted_max_rel => 0.5, # likewise
threshold_in_sorted_max_sec => 0, # likewise
threshold_factor_max => 1, # likewise
threshold_ratio => 0.15, # relative position between min/max
# Chunkification: smoothification
above_thres_window => 11, # in units of chunks
above_thres_window_rel => 0.25, # fractions of chunks above threshold
# in a window to make chunk signal
# Splitting into runs of signal/noise
max_tracks => 9999, # fail if more signal/noise runs
min_signal_sec => 5, # such runs of signal are forced
min_silence_sec => 2, # likewise
ignore_signal_sec => 1, # short runs of signal are ignored
min_silence_chunks_merge (see below) # and long resulting runs of silence
# are forced
# Calculate average signal in an interval "deeply inside" silence runs
local_level_ignore_pre_sec => 0.3, # offset the start of this interval
local_level_ignore_pre_rel => 0.02, # additional relative offset
local_level_ignore_post_sec => 0.3, # likewise for end of the interval
local_level_ignore_post_rel => 0.02, # likewise
# Enlargement of signal runs: attach consequent chunks with signal this much
# above this average over the neighbour silence run
local_threshold_factor => 1.05,
# Final enlargement of runs of signal
extend_track_end_sec => 0.5, # Unconditional enlargement
extend_track_begin_sec => 0.3, # likewise
min_boundary_silence_sec => 0.2, # Ignore short silence at start/end
Note that above_thres_window is the only value specified directly in units of chunks; the other *_sec may be optionally specified in units of chunks by setting the corresponding *_chunks value. Note also that this window should better be decreased if minimal allowed silence length parameters are decreased.
These values are mirrored from other values if not explicitly specified:
min_actual_silence_sec<<less
SYNOPSIS
use Audio::FindChunks;
# Duplicate input to output, caching RMS values to a file (as a side effect)
Audio::FindChunks->new(rms_filename => x.rms, filter => 1)->get(rms_data);
# Output human-readable info, using RMS cache file xxx.rms if present:
Audio::FindChunks->new(cache_rms => 1, filename => xxx.mp3,
stem_strip_extension => 1)->output_blocks();
# Remove start/end silence (if longer than 0.2sec):
Audio::FindChunks->new(cache_rms => 1, filename => xxx.mp3,
min_actual_silence_sec => 1e100)->split_file();
# Split a multiple-sides tape recording
Audio::FindChunks->new(filename => xxx.mp3, min_actual_silence_sec => 11
)->split_file({verbose => 1});
Audio sequence is broken into parts which contain only noise ("gaps"), and parts with usable signal ("tracks").
The following configuration settings (and defaults) are supported:
# For getting PCM flow (and if averaging data is read from cache)
frequency => 44100, # If raw_pcm or override_header_info only
bytes_per_sample => 4, # likewise
channels => 2, # likewise
sizedata => MY_INF, # likewise (how many bytes of PCM to read)
out_fh => *STDOUT, # mirror WAV/PCM to this FH if filter
# Process non-WAV data:
preprocess => {mp3 => [[qw(lame --silent --decode)], [], [-]]}, # Second contains extra args to read stdin
# RMS cache (used if valid_rms)
rms_extension => .rms, # Appended to the filestem
# Averaging to RMS info
sec_per_chunk => 0.1, # The window for taking mean square
# thresholds picking from the list of sorted 3-medians of RMS data
threshold_in_sorted_min_rel => 0, # relative position of threashold_min
threshold_in_sorted_min_sec => 1, # shifted by this amount in the list
threshold_factor_min => 1, # the list elt is multiplied by this
threshold_in_sorted_max_rel => 0.5, # likewise
threshold_in_sorted_max_sec => 0, # likewise
threshold_factor_max => 1, # likewise
threshold_ratio => 0.15, # relative position between min/max
# Chunkification: smoothification
above_thres_window => 11, # in units of chunks
above_thres_window_rel => 0.25, # fractions of chunks above threshold
# in a window to make chunk signal
# Splitting into runs of signal/noise
max_tracks => 9999, # fail if more signal/noise runs
min_signal_sec => 5, # such runs of signal are forced
min_silence_sec => 2, # likewise
ignore_signal_sec => 1, # short runs of signal are ignored
min_silence_chunks_merge (see below) # and long resulting runs of silence
# are forced
# Calculate average signal in an interval "deeply inside" silence runs
local_level_ignore_pre_sec => 0.3, # offset the start of this interval
local_level_ignore_pre_rel => 0.02, # additional relative offset
local_level_ignore_post_sec => 0.3, # likewise for end of the interval
local_level_ignore_post_rel => 0.02, # likewise
# Enlargement of signal runs: attach consequent chunks with signal this much
# above this average over the neighbour silence run
local_threshold_factor => 1.05,
# Final enlargement of runs of signal
extend_track_end_sec => 0.5, # Unconditional enlargement
extend_track_begin_sec => 0.3, # likewise
min_boundary_silence_sec => 0.2, # Ignore short silence at start/end
Note that above_thres_window is the only value specified directly in units of chunks; the other *_sec may be optionally specified in units of chunks by setting the corresponding *_chunks value. Note also that this window should better be decreased if minimal allowed silence length parameters are decreased.
These values are mirrored from other values if not explicitly specified:
min_actual_silence_sec<<less
Download (0.024MB)
Added: 2006-06-19 License: Perl Artistic License Price:
1222 downloads
Net-SSH2 0.09
Net-SSH2 is a SSH 2 protocol interface. more>>
Net-SSH2 is a SSH 2 protocol interface.
SYNOPSIS
Top
use Net::SSH2;
my $ssh2 = Net::SSH2->new();
$ssh2->connect(example.com) or die;
if ($ssh2->auth_keyboard(fizban)) {
my $chan = $ssh2->channel();
$chan->exec(program);
my $sftp = $ssh2->sftp();
my $fh = $sftp->open(/etc/passwd) or die;
print $_ while < $fh >;
}
Net::SSH2 is a perl interface to the libssh2 (http://www.libssh2.org) library. It supports the SSH2 protocol (there is no support for SSH1) with all of the key exchanges, ciphers, and compression of libssh2.
Unless otherwise indicated, methods return a true value on success and false on failure; use the error method to get extended error information.
The typical order is to create the SSH2 object, set up the connection methods you want to use, call connect, authenticate with one of the auth methods, then create channels on the connection to perform commands.
<<lessSYNOPSIS
Top
use Net::SSH2;
my $ssh2 = Net::SSH2->new();
$ssh2->connect(example.com) or die;
if ($ssh2->auth_keyboard(fizban)) {
my $chan = $ssh2->channel();
$chan->exec(program);
my $sftp = $ssh2->sftp();
my $fh = $sftp->open(/etc/passwd) or die;
print $_ while < $fh >;
}
Net::SSH2 is a perl interface to the libssh2 (http://www.libssh2.org) library. It supports the SSH2 protocol (there is no support for SSH1) with all of the key exchanges, ciphers, and compression of libssh2.
Unless otherwise indicated, methods return a true value on success and false on failure; use the error method to get extended error information.
The typical order is to create the SSH2 object, set up the connection methods you want to use, call connect, authenticate with one of the auth methods, then create channels on the connection to perform commands.
Download (0.064MB)
Added: 2006-09-28 License: Perl Artistic License Price:
1125 downloads
File::Sync 0.09
File::Sync is a Perl access to fsync() and sync() function calls. more>>
File::Sync is a Perl access to fsync() and sync() function calls.
SYNOPSIS
use File::Sync qw(fsync sync);
fsync(*FILEHANDLE) or die "fsync: $!";
sync();
use File::Sync qw(fsync);
use IO::File;
$fh = IO::File->new("> /tmp/foo")
or die "new IO::File: $!";
...
fsync($fh) or die "fsync: $!";
The fsync() function takes a Perl file handle as its only argument, and passes its fileno() to the C function fsync(). It returns undef on failure, or true on success.
The fsync_fd() function is used internally by fsync(); it takes a file descriptor as its only argument.
The sync() function is identical to the C function sync().
This module does not export any methods by default, but fsync() is made available as a method of the FileHandle and IO::Handle classes.
<<lessSYNOPSIS
use File::Sync qw(fsync sync);
fsync(*FILEHANDLE) or die "fsync: $!";
sync();
use File::Sync qw(fsync);
use IO::File;
$fh = IO::File->new("> /tmp/foo")
or die "new IO::File: $!";
...
fsync($fh) or die "fsync: $!";
The fsync() function takes a Perl file handle as its only argument, and passes its fileno() to the C function fsync(). It returns undef on failure, or true on success.
The fsync_fd() function is used internally by fsync(); it takes a file descriptor as its only argument.
The sync() function is identical to the C function sync().
This module does not export any methods by default, but fsync() is made available as a method of the FileHandle and IO::Handle classes.
Download (0.004MB)
Added: 2006-06-29 License: Perl Artistic License Price:
1213 downloads
File::MMagic 1.27
File::MMagic is a Perl module to guess file type. more>>
File::MMagic is a Perl module to guess file type.
SYNOPSIS
use File::MMagic;
use FileHandle;
$mm = new File::MMagic; # use internal magic file
# $mm = File::MMagic->new(/etc/magic); # use external magic file
# $mm = File::MMagic->new(/usr/share/etc/magic); # if you use Debian
$res = $mm->checktype_filename("/somewhere/unknown/file");
$fh = new FileHandle "< /somewhere/unknown/file2";
$res = $mm->checktype_filehandle($fh);
$fh->read($data, 0x8564);
$res = $mm->checktype_contents($data);
<<lessSYNOPSIS
use File::MMagic;
use FileHandle;
$mm = new File::MMagic; # use internal magic file
# $mm = File::MMagic->new(/etc/magic); # use external magic file
# $mm = File::MMagic->new(/usr/share/etc/magic); # if you use Debian
$res = $mm->checktype_filename("/somewhere/unknown/file");
$fh = new FileHandle "< /somewhere/unknown/file2";
$res = $mm->checktype_filehandle($fh);
$fh->read($data, 0x8564);
$res = $mm->checktype_contents($data);
Download (0.021MB)
Added: 2007-01-11 License: Perl Artistic License Price:
1017 downloads
File::lockf 0.20
File::lockf is a Perl module interface to the lockf system call. more>>
File::lockf is a Perl module interface to the lockf system call.
SYNOPSIS
use File::lockf;
File-Lockf is an interface to the lockf system call. Perl supports the flock system call natively, but that does not acquire network locks. Perl also supports the fcntl system call, but that is somewhat ugly to use. There are other locking modules available for Perl, but none of them provided what I wanted -- a simple, clean interface to the lockf system call, without any bells or whistles getting in the way.
File-Lockf contains four functions which map directly to the four modes of lockf, and an OO wrapper class that encapulates the basic locking functionality along with an additional utility method that iteratively attempts to acquire a lock.
Lock functions
The following functions return 0 (zero) on success, and the system error number from errno on failure. They each take an open file handle as the first argument, and optionally a size parameter. Please see your system lockf man page for more details about lockf functionality on your system.
$status = File::lockf::lock(FH, size = 0)
This function maps to the F_LOCK mode of lockf.
$status = File::lockf::tlock(FH, size = 0)
This function maps to the F_TLOCK mode of lockf.
$status = File::lockf::ulock(FH, size = 0)
This function maps to the F_ULOCK mode of lockf.
$status = File::lockf::test(FH, size = 0)
This function maps to the F_TEST mode of lockf.
OO wrapper
File-Lockf also provides a simple OO wrapper class around the locking functionality, which allows you to create a lock object for a file handle and then perform lock operations with it. All of the methods return 0 (zero) on success, and the system error number from errno on failure.
$lock = new File::lockf(*FH)
This function returns a new lock object bound to the given file handle. Note that you need to pass a reference to the file handle to the constructor, not the file handle itself.
$status = $lock->lock(size = 0)
This method calls File::lockf::lock on the bound file handle.
$status = $lock->tlock(size = 0)
This method calls File::lockf::tlock on the bound file handle.
$status = $lock->ulock(size = 0)
This method calls File::lockf::ulock on the bound file handle.
$status = $lock->test(size = 0)
This method calls File::lockf::test on the bound file handle.
$status = $lock->slock(count = 5, delay = 2, size = 0)
This method will attempt to lock the bound file handle < count > times, sleeping < delay > seconds after each try. It will return 0 if the lock succeeded, or the system error number from errno if all attempts fail.
<<lessSYNOPSIS
use File::lockf;
File-Lockf is an interface to the lockf system call. Perl supports the flock system call natively, but that does not acquire network locks. Perl also supports the fcntl system call, but that is somewhat ugly to use. There are other locking modules available for Perl, but none of them provided what I wanted -- a simple, clean interface to the lockf system call, without any bells or whistles getting in the way.
File-Lockf contains four functions which map directly to the four modes of lockf, and an OO wrapper class that encapulates the basic locking functionality along with an additional utility method that iteratively attempts to acquire a lock.
Lock functions
The following functions return 0 (zero) on success, and the system error number from errno on failure. They each take an open file handle as the first argument, and optionally a size parameter. Please see your system lockf man page for more details about lockf functionality on your system.
$status = File::lockf::lock(FH, size = 0)
This function maps to the F_LOCK mode of lockf.
$status = File::lockf::tlock(FH, size = 0)
This function maps to the F_TLOCK mode of lockf.
$status = File::lockf::ulock(FH, size = 0)
This function maps to the F_ULOCK mode of lockf.
$status = File::lockf::test(FH, size = 0)
This function maps to the F_TEST mode of lockf.
OO wrapper
File-Lockf also provides a simple OO wrapper class around the locking functionality, which allows you to create a lock object for a file handle and then perform lock operations with it. All of the methods return 0 (zero) on success, and the system error number from errno on failure.
$lock = new File::lockf(*FH)
This function returns a new lock object bound to the given file handle. Note that you need to pass a reference to the file handle to the constructor, not the file handle itself.
$status = $lock->lock(size = 0)
This method calls File::lockf::lock on the bound file handle.
$status = $lock->tlock(size = 0)
This method calls File::lockf::tlock on the bound file handle.
$status = $lock->ulock(size = 0)
This method calls File::lockf::ulock on the bound file handle.
$status = $lock->test(size = 0)
This method calls File::lockf::test on the bound file handle.
$status = $lock->slock(count = 5, delay = 2, size = 0)
This method will attempt to lock the bound file handle < count > times, sleeping < delay > seconds after each try. It will return 0 if the lock succeeded, or the system error number from errno if all attempts fail.
Download (0.003MB)
Added: 2007-04-27 License: Perl Artistic License Price:
911 downloads
RTF::Writer 1.11
RTF::Writer is a Perl module for generating documents in Rich Text Format. more>>
RTF::Writer is a Perl module for generating documents in Rich Text Format.
SYNOPSIS
use RTF::Writer;
my $rtf = RTF::Writer->new_to_file("greetings.rtf");
$rtf->prolog( title => "Greetings, hyoomon" );
$rtf->number_pages;
$rtf->paragraph(
fs40bi, # 20pt, bold, italic
"Hi there!"
);
$rtf->close;
This module is a class; an object belonging to this class acts like an output filehandle, and calling methods on it causes RTF text to be written.
Incidentally, this module also exports a few useful functions, upon request.
METHODS
$h = RTF::Writer->new_to_file($filename);
This creates a new RTF output stream object, such that sending text to this object will write to the filespec given. This is basically a wrapper around new_to_handle. If opening a write-handle to $filename fails (or if $filename is undef or zero-length), then a fatal error results.
$h = RTF::Writer->new_to_handle(*FILEHANDLE);
This creates a new RTF output stream object, such that sending text to this object will write to the filehandle given. The filehandle can be a glob (*FH) or a filehandle object (*FH{IO} or the value from IO::File->new(...)).
$h = RTF::Writer->new_to_string($string);
This creates a new RTF output stream object, such that sending text to this object will append to the string that youve passed a reference to.
$h->print(...);
This is the basic method for writing text to an RTF stream. This takes a list of items. Each item is either:
a plain string, like "foon"
In this case, the value is imputed to be a plaintext string, and an rtf-escaped version of it is written. For example "StuffnttUmmmn" causes Stuffline tab tab Ummline to be written. See rtfesc(x) for further details of escaping.
a scalar-reference, like ul
In this case, the value is imputed to be a reference to already escaped text. This is the basic way to emit RTF codes. Text passed this way will be written without any additional escaping.
Unless $RTF::Writer::AUTO_NL (normally on) has been turned off, the item written will be followed with a (presumably harmless) newline character to delimit any code in there from any following text, if the last character of this string is a digit or a lowercase letter. This is so that (i, "foo!") emits i[newline]foo! (which does what you expected), instead of ifoo!, which looks like an RTF command "ifoo" followed by a plaintext "!".
an array-reference, like [ ul, foo ]
This emits an open-brace "{", as RTF uses for opening "groups" (generally for delimiting the effects of character-formatting commands like ul, or a few formatting commands like footnote); then it emits the items in the referred-to array; and then emits a closing "}". I intend this to be useful is making sure that you dont emit more open-braces than close-braces, since that usually makes RTF readers immediately reject such a file.
You can nest these array-references, like:
$h->print(
col2,
[ pard,
"It is now ",
[ f1,
scalar(localtime), " local, or ",
scalar(gmtime), " GMT.",
],
" -- if youre ",
[ i,
"keeping track.",
],
],
parpage,
);
The return value of the print() method is currently always the value 1, although this may change.
$h->prolog(...);
This writes an RTF prolog to $h. You are free to make your own prolog using just $h->print(...your own code...), but I find in easier to automate this task, particularly with some sane defaults.
Since emitting a prolog opens a "{"-group, calling $h->prolog(...) sets a flag in $h so that when you call $h->close(), a closing "}" will automatically be written before the stream object is actually closed.
The options to the prolog() method are passed as a list of keys and values, for controlling the contents of the prolog written. The options are listed below, roughly with the most important options first.
(Be careful with the spelling of these options. Some are rather odd, because they are (mostly) based on the name of the relevent RTF command, and a systematic naming scheme for commands is one thing you wont find in RTF!)
fonts => [ "Courier New", "Georgia", "Whatever"...],
This value is for the font table section of the prolog. If the value is an arrayref, then it should be a reference to an array whose items should be either plain text strings, like "Times Roman", which are the (unescaped) names of fonts; or the items in the array can be scalar-refs, for expressing RTF control words along with the (escaped) font name, as in froman Times New Roman. If the value of the "fonts" parameters is a scalar ref, then it is taken to be a reference to code of your own that expresses the whole font table. If you dont specify a value for the "font" option, then you get a font table with one entry, "Times New Roman".
You should be sure to declare all fonts that you switch to in your document (as with f3, to change the current font to whats declared in entry 3 (counting from 0) in the font table).
deff => INTEGER,
This is for expressing, in the prolog, the font-table number of the default font for this document. The default is 0, which is an often useful value.
colors => [ undef, [0,142,252], [200,32,0], ...],
This value is for expressing the documents (generally optional) color table. If you stipulate an arrayref value, then each item of the array should be either an RGB triplet expressed as an arrayref like [200,32,0], or undef, for a null color-entry. If you stipulate a scalar-ref value for colors, then it is taken to be a reference to code of your own that expresses the whole font table.
If you dont stipulate any value for colors, then you get a table consisting of three colors: null/default (undef), 100% red ([2550,0,0]), and 100% blue ([0,0,255]).
You can freely ignore concerns of color tables if you dont use color-changing codes in your document (like cf2, to switch the text foreground color to whats declared at entry 2 (starting from 0) in the color table).
stylesheet => STRING,
filetbl => STRING,
listtables => STRING,
revtbl => STRING,
These are for expressing, in the prolog, code constituting the documents style sheet, table-of-files, table-of-lists, and table-of-revisions, respectively. The default value of each of these is empty-string. None of these are needed by a typical RTF document.
more_default => STRING,
This is for inserting any additional code just after the deffN in the start of the prolog, before the font table. A common useful value here is deflang1033, to express the default language (1033 = RTFese for US English) for the document, although my reading of the RTF spec leads me to believe that this doesnt need to be in the prolog here (where many writers put it, as apparently accepted by many RTF readers), but should (instead?) go just after the prolog, with other "document formatting" commands described in the "Document Formatting Properties" section of the RTF Specification.
doccomm => STRING,
This value is for the "document comment" metainformation item in the prolog, which appears as the "Comment" field in the "File Properties" panel in MSWord, or as the "Abstract" field in the "File Properties" window in WordPerfect.
If no value is specified, then RTF::Writer puts a string noting the value of $0 (typically the filespec to the current Perl program), and the version of RTF::Writer used.
title => STRING,
subject => STRING,
author => STRING,
manager => STRING,
company => STRING,
operator => STRING,
category => STRING,
keywords => STRING,
hlinkbase => STRING,
comment => STRING,
These are for stipulating the string values of these various optional document metainformation items. operator is for the name of the person who last made changes to the document; hlinkbase is which is the URL or path that is used for for resolving any all relative hyperlinks in the document; comment is reportedly just ignored (cf. the doccomm attribute, which is not ignored); and you can guess the rest.
The meanings of all of these are explained in greater detail in the RTF spec.
revtim => EPOCH_NUMBER,
This value is for the document metainformation section of the prolog. It signifies the last-modified time of the document. EPOCH_NUMBER is the number of seconds since the epoch, such as one gets from (stat($thing)[9]) or time(); or you may pass a reference a timelist, like [localtime($whatever)].
If no defined value for revtime is stipulated in the call to prolog(...) then the current value of time() is used. Explicitly pass a value of undef to suppress emitting any creatim value.
creatim => EPOCH_NUMBER,
This value is for the document metainformation section of the prolog. It signifies the last-modified time of the document. If no defined value for creatim is stipulated in the call to prolog(...) then the current value of time() is used. Explicitly pass a value of undef to suppress emitting any creatim value.
printim => EPOCH_NUMBER,
This value is for the document metainformation section of the prolog. It signifies the time when this document was last printed. If you dont stipulate a defined value here, no printim metainformation is written.
buptim => EPOCH_NUMBER,
This value is for the document metainformation section of the prolog. It signifies the "backup time" of this document. If you dont stipulate a defined value here, no buptim metainformation is written.
version => INTEGER,
vern => INTEGER,
edmins => INTEGER,
nofpages => INTEGER,
nofwords => INTEGER,
nofchars => INTEGER,
nofcharsws => INTEGER,
id => INTEGER,
These are for stipulating the integer values of these various optional (and not terribly useful, for most purposes!) document metainformation items. The meanings of all of these are explained in the RTF spec.
charset => STRING,
This is for expressing, in the prolog, RTF codename for the character set being used in this document. The default is "ansi", and dont stipulate anything else (like "mac", "pc", or "pca") unless you know what youre doing.
rtf_version => INTEGER,
This is for expressing, in the prolog, what major version of RTF is being used in this document. The default is 1, and dont use anything else unless you really know what youre doing.
$h->printf(format, ...items...);
This is just short for $h->print(sprintf(format, ...items...)
$h->printf(format, ...items...);
In this case, format is assumed to contain already-escaped RTF code. The items in ...items... are escaped as necessary, and then interpolated. I.e., this is rather like: $h->print(sprintf format, map rtfesc($_), ...items...)) except that numeric items dont get escaped (and dont need to be). Example:
$h->printf(
{i "%s"} was found in %2.2f percent of matchespar,
$word, 100 * $count / $total
);
$h->number_pages();
$h->number_pages(...);
This is just a handy wrapper for some code that turns on page numbering. If you call this method, you should call it right after you emit a prolog.
The page numbering consists of just putting the page number at the top-right of each page. If you provide items in the list (...), then that is pre-pended to the page number. Example:
$h->number_pages("Lexicon, p.");
Or:
$h->number_pages(bfs30f2, "page ");
$trdecl = RTF::Writer::TableRowDecl->new( ...options... )
This constructs an object representing a declaration for a table row. You can have to use it in calls to $h->row($tabldecl,...), and can reuse it on subsequent calls. This object is for declaring the dimensions of table rows.
The work that a declaration has to do, is best explained in this diagram of a bordered three-cell table (first cell containing "Foo ya!"), placed near a left margin (shown as the line of colons). The things in brackets are not on the page, but just for our reference:
: [..w1...]
: [......w2.......]
: [...w3....]
[.A..] [.B.] [.B.]
:
: +-------+---------------+---------+
: | Foo | Bar baz | Yee! |
: | ya! | quuxi quuxo | |
: | | quaqua. | |
: +-------+---------------+---------+
:
[.A..] [.B.] [.B.]
[..r1........]
[.....r2.....................]
[........r3............................]
Here the horizontal dimensions of the three-celled table are expressed in terms of: A, the distance from the current left margin; B, the minimum distance between the content of the cells (or you can think of this as twice the internal left or right borders in each cell); and then EITHER [w1, w2, w3], expressing the width of each cell, OR [r1, r2, r3], expressing each cells right ends distance from the current left margin. All distances are, of course, in twips.
Options to RTF::Writer::TableRowDecl->new( ...options... ) are:
left_start => TWIPS,
This declares the distance between the left margin, and the left end of the table. Default is 0.
inbetween => TWIPS,
This declares the distance labelled "B", above. Default is 120, which is 6 points, 1/12th-inch, about 2mm.
widths => [TWIPS, TWIPS, TWIPS, ... ],
This expresses the widths of each of the cells in this row, starting from the leftmost.
reaches => [TWIPS, TWIPS, TWIPS, ... ],
This expresses the rightmost extreme of each of the cells in this row.
align => alignmentspecs,
This is explained in detail in the section "Cell Alignment Syntax", below.
borders => borderspecs,
This is explained in detail in the section "Cell Border Syntax", below.
$h->paragraph(...);
This makes the items in the list (...) into a paragraph. Basically just a wrapper for $h->print([ {par, ..., pard}, ])
$h->row($trdecl, ...items...);
This emits a table row, with dimensions as stipulated by the $trdecl object, and with row content from the items given.
You must provide a value for $trdecl, or a fatal error results.
If you provide fewer items than $trdecl declares cells, then you get empty cells to fill out the row. If you provide more items than $trdecl declares cells, then the width of the last declared row is used in figuring the width of the additional cells for this row.
Example:
my $decl = RTF::Writer::TableRowDecl->new(widths => [1500,1900]);
$h->row($decl, "Stuff", "Hmmm");
$h->row($decl, [ul, Foo], Bar, bullet);
$h->row($decl, "Hooboy.");
This creates a table resembing:
+-------------+-------------------+
| Stuff | Hmm |
+-------------+-------------------+-------------------+
| _Foo_ | Bar | * |
+-------------+-------------------+-------------------+
| "Hooboy." | |
+-------------+-------------------+
Note that you MUST NOT use par commands in any items you emit in row cells!
The $h->row(...) method is a wrapper for producing elementary tables in RTF, with the minimum of parameters; the myriad other options that tables can have (for example, changing borders) are not supported. If you really need to generate tables fancier than what $h->row(...) can produce, start off reading the RTF spec, reading the source for row() (and the RTF::Writer::TableRowDecl class), and progress from there. Note that MSWord has been known to crash when given malformed RTF table code.
$h->table($trdecl, [...row1 items...], [...row2 items...], ... );
$h->table([...row1 items...], [...row2 items...], ... );
This is a wrapper around $h->row. It takes a list of arrayrefs, which are fed to calls to h->row($tr_decl, @$each_arrayref). You should provide a $trdecl, but if you dont, then one is crudely guessed at, based on the maximum number of columns in all rows.
$h->image( image_parameters )
This returns a scalar-reference to RTF-code representing the given image with given parameters. For example:
$h->paragraph(
"See here: ",
$h->image( filename => "foo.png", ),
);
The legal options are explained below:
filename => FILENAME,
This should be the path to a readable filename. You have to specify this. If you dont specify this, or if the value isnt a readable file, then a fatal error results. Currently, only JPEGs and PNGs are allowed; specifying any other kind of file causes a fatal error.
(The filename option above is required, but the following options are all generally optional -- altho some RTF processors may be finicky if you set some of the following but not others, for no apparent reason. When in doubt, test.)
wgoal => TWIPS,
The desired width of the image
hgoal => TWIPS,
The desired height of the image
scalex => PERCENT,
scaley => PERCENT,
Respectively, the horizontal (X) or vertical (Y) scaling value. The argument is an integer representing a percentage. (The default is 100 percent)
cropt => TWIPS,
cropb => TWIPS,
cropl => TWIPS,
cropr => TWIPS,
These specify the top, bottom, left, and right cropping values. A positive value crops toward the center of the image. A negative value crops away from the center, adding a padding space around the image.
(The default is to do neither, as youd get from a cropping value of 0.)
picspecs => SCALARVALUE,
This overrides generation of the normal image values based the image and the above parameters, and instead uses whatever value you pass a reference to. You normally shouldnt need to use this.
$h->image_paragraph( image_parameters );
This take the same options as $h->image(...), but has three differences: First, it is a shortcut for this:
$h->paragraph( qc,
$h->image( ...params...),
);
Secondly, whereas $h->image(...) returns the image data (as an RTF scalarref), $h->image_paragraph(...) doesnt return much of anything.
Thirdly, $h->image_paragraph(...) is often much more memory-efficient, since it can write the image data to a file as its RTF-ified, instead of building it all up in memory.
$h->close();
This completes writing to the stream denoted by the object in $h; this generally (assuming youd called $h->prolog) involves just writing a final close-brace to $h, and then closing whatever filehandle or file $h writes to (unless were writing to a string, in which case we just discard $hs reference to it). After you call $h->close, you should not call any other methods with $h!
Note that you dont have to explicitly call $h->close -- when an unclosed RTF::Writer object goes out of scope (or, more precisely speaking, when if its refcount hits zero), then something equivalent to calling $h->close is done automatically for you.
<<lessSYNOPSIS
use RTF::Writer;
my $rtf = RTF::Writer->new_to_file("greetings.rtf");
$rtf->prolog( title => "Greetings, hyoomon" );
$rtf->number_pages;
$rtf->paragraph(
fs40bi, # 20pt, bold, italic
"Hi there!"
);
$rtf->close;
This module is a class; an object belonging to this class acts like an output filehandle, and calling methods on it causes RTF text to be written.
Incidentally, this module also exports a few useful functions, upon request.
METHODS
$h = RTF::Writer->new_to_file($filename);
This creates a new RTF output stream object, such that sending text to this object will write to the filespec given. This is basically a wrapper around new_to_handle. If opening a write-handle to $filename fails (or if $filename is undef or zero-length), then a fatal error results.
$h = RTF::Writer->new_to_handle(*FILEHANDLE);
This creates a new RTF output stream object, such that sending text to this object will write to the filehandle given. The filehandle can be a glob (*FH) or a filehandle object (*FH{IO} or the value from IO::File->new(...)).
$h = RTF::Writer->new_to_string($string);
This creates a new RTF output stream object, such that sending text to this object will append to the string that youve passed a reference to.
$h->print(...);
This is the basic method for writing text to an RTF stream. This takes a list of items. Each item is either:
a plain string, like "foon"
In this case, the value is imputed to be a plaintext string, and an rtf-escaped version of it is written. For example "StuffnttUmmmn" causes Stuffline tab tab Ummline to be written. See rtfesc(x) for further details of escaping.
a scalar-reference, like ul
In this case, the value is imputed to be a reference to already escaped text. This is the basic way to emit RTF codes. Text passed this way will be written without any additional escaping.
Unless $RTF::Writer::AUTO_NL (normally on) has been turned off, the item written will be followed with a (presumably harmless) newline character to delimit any code in there from any following text, if the last character of this string is a digit or a lowercase letter. This is so that (i, "foo!") emits i[newline]foo! (which does what you expected), instead of ifoo!, which looks like an RTF command "ifoo" followed by a plaintext "!".
an array-reference, like [ ul, foo ]
This emits an open-brace "{", as RTF uses for opening "groups" (generally for delimiting the effects of character-formatting commands like ul, or a few formatting commands like footnote); then it emits the items in the referred-to array; and then emits a closing "}". I intend this to be useful is making sure that you dont emit more open-braces than close-braces, since that usually makes RTF readers immediately reject such a file.
You can nest these array-references, like:
$h->print(
col2,
[ pard,
"It is now ",
[ f1,
scalar(localtime), " local, or ",
scalar(gmtime), " GMT.",
],
" -- if youre ",
[ i,
"keeping track.",
],
],
parpage,
);
The return value of the print() method is currently always the value 1, although this may change.
$h->prolog(...);
This writes an RTF prolog to $h. You are free to make your own prolog using just $h->print(...your own code...), but I find in easier to automate this task, particularly with some sane defaults.
Since emitting a prolog opens a "{"-group, calling $h->prolog(...) sets a flag in $h so that when you call $h->close(), a closing "}" will automatically be written before the stream object is actually closed.
The options to the prolog() method are passed as a list of keys and values, for controlling the contents of the prolog written. The options are listed below, roughly with the most important options first.
(Be careful with the spelling of these options. Some are rather odd, because they are (mostly) based on the name of the relevent RTF command, and a systematic naming scheme for commands is one thing you wont find in RTF!)
fonts => [ "Courier New", "Georgia", "Whatever"...],
This value is for the font table section of the prolog. If the value is an arrayref, then it should be a reference to an array whose items should be either plain text strings, like "Times Roman", which are the (unescaped) names of fonts; or the items in the array can be scalar-refs, for expressing RTF control words along with the (escaped) font name, as in froman Times New Roman. If the value of the "fonts" parameters is a scalar ref, then it is taken to be a reference to code of your own that expresses the whole font table. If you dont specify a value for the "font" option, then you get a font table with one entry, "Times New Roman".
You should be sure to declare all fonts that you switch to in your document (as with f3, to change the current font to whats declared in entry 3 (counting from 0) in the font table).
deff => INTEGER,
This is for expressing, in the prolog, the font-table number of the default font for this document. The default is 0, which is an often useful value.
colors => [ undef, [0,142,252], [200,32,0], ...],
This value is for expressing the documents (generally optional) color table. If you stipulate an arrayref value, then each item of the array should be either an RGB triplet expressed as an arrayref like [200,32,0], or undef, for a null color-entry. If you stipulate a scalar-ref value for colors, then it is taken to be a reference to code of your own that expresses the whole font table.
If you dont stipulate any value for colors, then you get a table consisting of three colors: null/default (undef), 100% red ([2550,0,0]), and 100% blue ([0,0,255]).
You can freely ignore concerns of color tables if you dont use color-changing codes in your document (like cf2, to switch the text foreground color to whats declared at entry 2 (starting from 0) in the color table).
stylesheet => STRING,
filetbl => STRING,
listtables => STRING,
revtbl => STRING,
These are for expressing, in the prolog, code constituting the documents style sheet, table-of-files, table-of-lists, and table-of-revisions, respectively. The default value of each of these is empty-string. None of these are needed by a typical RTF document.
more_default => STRING,
This is for inserting any additional code just after the deffN in the start of the prolog, before the font table. A common useful value here is deflang1033, to express the default language (1033 = RTFese for US English) for the document, although my reading of the RTF spec leads me to believe that this doesnt need to be in the prolog here (where many writers put it, as apparently accepted by many RTF readers), but should (instead?) go just after the prolog, with other "document formatting" commands described in the "Document Formatting Properties" section of the RTF Specification.
doccomm => STRING,
This value is for the "document comment" metainformation item in the prolog, which appears as the "Comment" field in the "File Properties" panel in MSWord, or as the "Abstract" field in the "File Properties" window in WordPerfect.
If no value is specified, then RTF::Writer puts a string noting the value of $0 (typically the filespec to the current Perl program), and the version of RTF::Writer used.
title => STRING,
subject => STRING,
author => STRING,
manager => STRING,
company => STRING,
operator => STRING,
category => STRING,
keywords => STRING,
hlinkbase => STRING,
comment => STRING,
These are for stipulating the string values of these various optional document metainformation items. operator is for the name of the person who last made changes to the document; hlinkbase is which is the URL or path that is used for for resolving any all relative hyperlinks in the document; comment is reportedly just ignored (cf. the doccomm attribute, which is not ignored); and you can guess the rest.
The meanings of all of these are explained in greater detail in the RTF spec.
revtim => EPOCH_NUMBER,
This value is for the document metainformation section of the prolog. It signifies the last-modified time of the document. EPOCH_NUMBER is the number of seconds since the epoch, such as one gets from (stat($thing)[9]) or time(); or you may pass a reference a timelist, like [localtime($whatever)].
If no defined value for revtime is stipulated in the call to prolog(...) then the current value of time() is used. Explicitly pass a value of undef to suppress emitting any creatim value.
creatim => EPOCH_NUMBER,
This value is for the document metainformation section of the prolog. It signifies the last-modified time of the document. If no defined value for creatim is stipulated in the call to prolog(...) then the current value of time() is used. Explicitly pass a value of undef to suppress emitting any creatim value.
printim => EPOCH_NUMBER,
This value is for the document metainformation section of the prolog. It signifies the time when this document was last printed. If you dont stipulate a defined value here, no printim metainformation is written.
buptim => EPOCH_NUMBER,
This value is for the document metainformation section of the prolog. It signifies the "backup time" of this document. If you dont stipulate a defined value here, no buptim metainformation is written.
version => INTEGER,
vern => INTEGER,
edmins => INTEGER,
nofpages => INTEGER,
nofwords => INTEGER,
nofchars => INTEGER,
nofcharsws => INTEGER,
id => INTEGER,
These are for stipulating the integer values of these various optional (and not terribly useful, for most purposes!) document metainformation items. The meanings of all of these are explained in the RTF spec.
charset => STRING,
This is for expressing, in the prolog, RTF codename for the character set being used in this document. The default is "ansi", and dont stipulate anything else (like "mac", "pc", or "pca") unless you know what youre doing.
rtf_version => INTEGER,
This is for expressing, in the prolog, what major version of RTF is being used in this document. The default is 1, and dont use anything else unless you really know what youre doing.
$h->printf(format, ...items...);
This is just short for $h->print(sprintf(format, ...items...)
$h->printf(format, ...items...);
In this case, format is assumed to contain already-escaped RTF code. The items in ...items... are escaped as necessary, and then interpolated. I.e., this is rather like: $h->print(sprintf format, map rtfesc($_), ...items...)) except that numeric items dont get escaped (and dont need to be). Example:
$h->printf(
{i "%s"} was found in %2.2f percent of matchespar,
$word, 100 * $count / $total
);
$h->number_pages();
$h->number_pages(...);
This is just a handy wrapper for some code that turns on page numbering. If you call this method, you should call it right after you emit a prolog.
The page numbering consists of just putting the page number at the top-right of each page. If you provide items in the list (...), then that is pre-pended to the page number. Example:
$h->number_pages("Lexicon, p.");
Or:
$h->number_pages(bfs30f2, "page ");
$trdecl = RTF::Writer::TableRowDecl->new( ...options... )
This constructs an object representing a declaration for a table row. You can have to use it in calls to $h->row($tabldecl,...), and can reuse it on subsequent calls. This object is for declaring the dimensions of table rows.
The work that a declaration has to do, is best explained in this diagram of a bordered three-cell table (first cell containing "Foo ya!"), placed near a left margin (shown as the line of colons). The things in brackets are not on the page, but just for our reference:
: [..w1...]
: [......w2.......]
: [...w3....]
[.A..] [.B.] [.B.]
:
: +-------+---------------+---------+
: | Foo | Bar baz | Yee! |
: | ya! | quuxi quuxo | |
: | | quaqua. | |
: +-------+---------------+---------+
:
[.A..] [.B.] [.B.]
[..r1........]
[.....r2.....................]
[........r3............................]
Here the horizontal dimensions of the three-celled table are expressed in terms of: A, the distance from the current left margin; B, the minimum distance between the content of the cells (or you can think of this as twice the internal left or right borders in each cell); and then EITHER [w1, w2, w3], expressing the width of each cell, OR [r1, r2, r3], expressing each cells right ends distance from the current left margin. All distances are, of course, in twips.
Options to RTF::Writer::TableRowDecl->new( ...options... ) are:
left_start => TWIPS,
This declares the distance between the left margin, and the left end of the table. Default is 0.
inbetween => TWIPS,
This declares the distance labelled "B", above. Default is 120, which is 6 points, 1/12th-inch, about 2mm.
widths => [TWIPS, TWIPS, TWIPS, ... ],
This expresses the widths of each of the cells in this row, starting from the leftmost.
reaches => [TWIPS, TWIPS, TWIPS, ... ],
This expresses the rightmost extreme of each of the cells in this row.
align => alignmentspecs,
This is explained in detail in the section "Cell Alignment Syntax", below.
borders => borderspecs,
This is explained in detail in the section "Cell Border Syntax", below.
$h->paragraph(...);
This makes the items in the list (...) into a paragraph. Basically just a wrapper for $h->print([ {par, ..., pard}, ])
$h->row($trdecl, ...items...);
This emits a table row, with dimensions as stipulated by the $trdecl object, and with row content from the items given.
You must provide a value for $trdecl, or a fatal error results.
If you provide fewer items than $trdecl declares cells, then you get empty cells to fill out the row. If you provide more items than $trdecl declares cells, then the width of the last declared row is used in figuring the width of the additional cells for this row.
Example:
my $decl = RTF::Writer::TableRowDecl->new(widths => [1500,1900]);
$h->row($decl, "Stuff", "Hmmm");
$h->row($decl, [ul, Foo], Bar, bullet);
$h->row($decl, "Hooboy.");
This creates a table resembing:
+-------------+-------------------+
| Stuff | Hmm |
+-------------+-------------------+-------------------+
| _Foo_ | Bar | * |
+-------------+-------------------+-------------------+
| "Hooboy." | |
+-------------+-------------------+
Note that you MUST NOT use par commands in any items you emit in row cells!
The $h->row(...) method is a wrapper for producing elementary tables in RTF, with the minimum of parameters; the myriad other options that tables can have (for example, changing borders) are not supported. If you really need to generate tables fancier than what $h->row(...) can produce, start off reading the RTF spec, reading the source for row() (and the RTF::Writer::TableRowDecl class), and progress from there. Note that MSWord has been known to crash when given malformed RTF table code.
$h->table($trdecl, [...row1 items...], [...row2 items...], ... );
$h->table([...row1 items...], [...row2 items...], ... );
This is a wrapper around $h->row. It takes a list of arrayrefs, which are fed to calls to h->row($tr_decl, @$each_arrayref). You should provide a $trdecl, but if you dont, then one is crudely guessed at, based on the maximum number of columns in all rows.
$h->image( image_parameters )
This returns a scalar-reference to RTF-code representing the given image with given parameters. For example:
$h->paragraph(
"See here: ",
$h->image( filename => "foo.png", ),
);
The legal options are explained below:
filename => FILENAME,
This should be the path to a readable filename. You have to specify this. If you dont specify this, or if the value isnt a readable file, then a fatal error results. Currently, only JPEGs and PNGs are allowed; specifying any other kind of file causes a fatal error.
(The filename option above is required, but the following options are all generally optional -- altho some RTF processors may be finicky if you set some of the following but not others, for no apparent reason. When in doubt, test.)
wgoal => TWIPS,
The desired width of the image
hgoal => TWIPS,
The desired height of the image
scalex => PERCENT,
scaley => PERCENT,
Respectively, the horizontal (X) or vertical (Y) scaling value. The argument is an integer representing a percentage. (The default is 100 percent)
cropt => TWIPS,
cropb => TWIPS,
cropl => TWIPS,
cropr => TWIPS,
These specify the top, bottom, left, and right cropping values. A positive value crops toward the center of the image. A negative value crops away from the center, adding a padding space around the image.
(The default is to do neither, as youd get from a cropping value of 0.)
picspecs => SCALARVALUE,
This overrides generation of the normal image values based the image and the above parameters, and instead uses whatever value you pass a reference to. You normally shouldnt need to use this.
$h->image_paragraph( image_parameters );
This take the same options as $h->image(...), but has three differences: First, it is a shortcut for this:
$h->paragraph( qc,
$h->image( ...params...),
);
Secondly, whereas $h->image(...) returns the image data (as an RTF scalarref), $h->image_paragraph(...) doesnt return much of anything.
Thirdly, $h->image_paragraph(...) is often much more memory-efficient, since it can write the image data to a file as its RTF-ified, instead of building it all up in memory.
$h->close();
This completes writing to the stream denoted by the object in $h; this generally (assuming youd called $h->prolog) involves just writing a final close-brace to $h, and then closing whatever filehandle or file $h writes to (unless were writing to a string, in which case we just discard $hs reference to it). After you call $h->close, you should not call any other methods with $h!
Note that you dont have to explicitly call $h->close -- when an unclosed RTF::Writer object goes out of scope (or, more precisely speaking, when if its refcount hits zero), then something equivalent to calling $h->close is done automatically for you.
Download (0.056MB)
Added: 2007-07-17 License: Perl Artistic License Price:
515 downloads
Text::Refer 1.106
Text::Refer can parse Unix refer files. more>>
Text::Refer can parse Unix "refer" files.
SYNOPSIS
Pull in the module:
use Text::Refer;
Parse a refer stream from a filehandle:
while ($ref = input Text::Refer *FH) {
# ...do stuff with $ref...
}
defined($ref) or die "error parsing input";
Same, but using a parser object for more control:
# Create a new parser:
$parser = new Text::Refer::Parser LeadWhite=>KEEP;
# Parse:
while ($ref = $parser->input(*FH)) {
# ...do stuff with $ref...
}
defined($ref) or die "error parsing input";
Manipulating reference objects, using high-level methods:
# Get the title, author, etc.:
$title = $ref->title;
@authors = $ref->author; # list context
$lastAuthor = $ref->author; # scalar context
# Set the title and authors:
$ref->title("Cyberiad");
$ref->author(["S. Trurl", "C. Klapaucius"]); # arrayref for >1 value!
# Delete the abstract:
$ref->abstract(undef);
Same, using low-level methods:
# Get the title, author, etc.:
$title = $ref->get(T);
@authors = $ref->get(A); # list context
$lastAuthor = $ref->get(A); # scalar context
# Set the title and authors:
$ref->set(T, "Cyberiad");
$ref->set(A, "S. Trurl", "C. Klapaucius");
# Delete the abstract:
$ref->set(X); # sets to empty array of values
Output:
print $ref->as_string;
<<lessSYNOPSIS
Pull in the module:
use Text::Refer;
Parse a refer stream from a filehandle:
while ($ref = input Text::Refer *FH) {
# ...do stuff with $ref...
}
defined($ref) or die "error parsing input";
Same, but using a parser object for more control:
# Create a new parser:
$parser = new Text::Refer::Parser LeadWhite=>KEEP;
# Parse:
while ($ref = $parser->input(*FH)) {
# ...do stuff with $ref...
}
defined($ref) or die "error parsing input";
Manipulating reference objects, using high-level methods:
# Get the title, author, etc.:
$title = $ref->title;
@authors = $ref->author; # list context
$lastAuthor = $ref->author; # scalar context
# Set the title and authors:
$ref->title("Cyberiad");
$ref->author(["S. Trurl", "C. Klapaucius"]); # arrayref for >1 value!
# Delete the abstract:
$ref->abstract(undef);
Same, using low-level methods:
# Get the title, author, etc.:
$title = $ref->get(T);
@authors = $ref->get(A); # list context
$lastAuthor = $ref->get(A); # scalar context
# Set the title and authors:
$ref->set(T, "Cyberiad");
$ref->set(A, "S. Trurl", "C. Klapaucius");
# Delete the abstract:
$ref->set(X); # sets to empty array of values
Output:
print $ref->as_string;
Download (0.031MB)
Added: 2007-08-22 License: Perl Artistic License Price:
794 downloads
HTML::Parser 3.54
HTML::Parser is a HTML parser class. more>>
HTML::Parser is a HTML parser class. Objects of the HTML::Parser class will recognize markup and separate it from plain text (alias data content) in HTML documents. As different kinds of markup and text are recognized, the corresponding event handlers are invoked.
HTML::Parser is not a generic SGML parser.
We have tried to make it able to deal with the HTML that is actually "out there", and it normally parses as closely as possible to the way the popular web browsers do it instead of strictly following one of the many HTML specifications from W3C. Where there is disagreement, there is often an option that you can enable to get the official behaviour.
The document to be parsed may be supplied in arbitrary chunks. This makes on-the-fly parsing as documents are received from the network possible.
If event driven parsing does not feel right for your application, you might want to use HTML::PullParser. This is an HTML::Parser subclass that allows a more conventional program structure.
SYNOPSIS:
use HTML::Parser ();
# Create parser object
$p = HTML::Parser->new( api_version => 3,
start_h => [&start, "tagname, attr"],
end_h => [&end, "tagname"],
marked_sections => 1,
);
# Parse document text chunk by chunk
$p->parse($chunk1);
$p->parse($chunk2);
#...
$p->eof; # signal end of document
# Parse directly from file
$p->parse_file("foo.html");
# or
open(my $fh, "<<less
HTML::Parser is not a generic SGML parser.
We have tried to make it able to deal with the HTML that is actually "out there", and it normally parses as closely as possible to the way the popular web browsers do it instead of strictly following one of the many HTML specifications from W3C. Where there is disagreement, there is often an option that you can enable to get the official behaviour.
The document to be parsed may be supplied in arbitrary chunks. This makes on-the-fly parsing as documents are received from the network possible.
If event driven parsing does not feel right for your application, you might want to use HTML::PullParser. This is an HTML::Parser subclass that allows a more conventional program structure.
SYNOPSIS:
use HTML::Parser ();
# Create parser object
$p = HTML::Parser->new( api_version => 3,
start_h => [&start, "tagname, attr"],
end_h => [&end, "tagname"],
marked_sections => 1,
);
# Parse document text chunk by chunk
$p->parse($chunk1);
$p->parse($chunk2);
#...
$p->eof; # signal end of document
# Parse directly from file
$p->parse_file("foo.html");
# or
open(my $fh, "<<less
Download (0.082MB)
Added: 2006-05-05 License: Perl Artistic License Price:
1269 downloads
Proc::Forking 1.38
Proc::Forking is a Perl module that provides a set of tool to fork and daemonize. more>>
Proc::Forking is a Perl module that provides a set of tool to fork and daemonize.
SYNOPSIS
#!/usr/bin/perl
use strict;
use Proc::Forking;
use Data::Dumper;
use Time::HiRes qw(usleep); # to allow micro sleep
my $f = Proc::Forking->new();
$SIG{ KILL } = $SIG{ TERM } = $SIG{ INT } = sub { $f->killall_childs;sleep 1; exit },
$f->daemonize(
## uid => 1000,
## gid => 1000,
## home => "/tmp",
pid_file => "/tmp/master.pid"
);
open( STDOUT, ">>/tmp/master.log" );
my $nbr = 0;
my $timemout;
while ( 1 )
{
if ( $nbr < 20 )
{
my $extra = "other parameter";
my ( $status, $pid, $error ) = $f->fork_child(
function => &func,
name => "new_name.##",
args => [ "hello SOMEONE", 3, $extra ],
pid_file => "/tmp/fork.##.pid",
uid => 1000,
gid => 1000,
home => "/tmp",
max_load => 5,
max_mem => 185000000,
expiration => 10,
# expiration_auto => 1,
);
if ( $status == 4 ) # if the load become to high
{
print "Max load reached, do a little napn";
usleep( 100000 );
next;
}
elsif ( $status ) # if another kind of error
{
print "PID=$pidt error=$errorn";
print Dumper( $f->list_names() );
print Dumper( $f->list_pids() );
}
}
$nbr = $f->pid_nbr;
my ( $n, @dp, @dn ) = $f->expirate;
if ( $n )
{
print Dumper( @dp );
}
print "free=n";
usleep( 100000 ); # always a good idea to put a small sleep to allow task swapper to gain some free resources
}
sub func
{
my $ref = shift;
my @args = @$ref;
my ( $data, $time_out, $sockC ) = @args;
$SIG{ USR1 } = sub { open my $log, ">>/tmp/log.s"; print $log "signal USR1 receivedn"; close $log; };
if ( !$time_out )
{
$time_out = 3;
}
open my $FF, ">>/tmp/loglist";
print $FF $$, " start time =", $^T;
close $FF;
for ( 1 .. 4 )
{
open my $fh, ">>/tmp/log";
if ( defined $fh )
{
print $fh "TMOUT = $time_out " . time . " PID=$$ cwd=" . Cwd::cwd() . " name =$0n";
$fh->close;
}
sleep $time_out + rand( 5 );
}
}
<<lessSYNOPSIS
#!/usr/bin/perl
use strict;
use Proc::Forking;
use Data::Dumper;
use Time::HiRes qw(usleep); # to allow micro sleep
my $f = Proc::Forking->new();
$SIG{ KILL } = $SIG{ TERM } = $SIG{ INT } = sub { $f->killall_childs;sleep 1; exit },
$f->daemonize(
## uid => 1000,
## gid => 1000,
## home => "/tmp",
pid_file => "/tmp/master.pid"
);
open( STDOUT, ">>/tmp/master.log" );
my $nbr = 0;
my $timemout;
while ( 1 )
{
if ( $nbr < 20 )
{
my $extra = "other parameter";
my ( $status, $pid, $error ) = $f->fork_child(
function => &func,
name => "new_name.##",
args => [ "hello SOMEONE", 3, $extra ],
pid_file => "/tmp/fork.##.pid",
uid => 1000,
gid => 1000,
home => "/tmp",
max_load => 5,
max_mem => 185000000,
expiration => 10,
# expiration_auto => 1,
);
if ( $status == 4 ) # if the load become to high
{
print "Max load reached, do a little napn";
usleep( 100000 );
next;
}
elsif ( $status ) # if another kind of error
{
print "PID=$pidt error=$errorn";
print Dumper( $f->list_names() );
print Dumper( $f->list_pids() );
}
}
$nbr = $f->pid_nbr;
my ( $n, @dp, @dn ) = $f->expirate;
if ( $n )
{
print Dumper( @dp );
}
print "free=n";
usleep( 100000 ); # always a good idea to put a small sleep to allow task swapper to gain some free resources
}
sub func
{
my $ref = shift;
my @args = @$ref;
my ( $data, $time_out, $sockC ) = @args;
$SIG{ USR1 } = sub { open my $log, ">>/tmp/log.s"; print $log "signal USR1 receivedn"; close $log; };
if ( !$time_out )
{
$time_out = 3;
}
open my $FF, ">>/tmp/loglist";
print $FF $$, " start time =", $^T;
close $FF;
for ( 1 .. 4 )
{
open my $fh, ">>/tmp/log";
if ( defined $fh )
{
print $fh "TMOUT = $time_out " . time . " PID=$$ cwd=" . Cwd::cwd() . " name =$0n";
$fh->close;
}
sleep $time_out + rand( 5 );
}
}
Download (0.011MB)
Added: 2007-03-06 License: Perl Artistic License Price:
962 downloads
InfoSys::FreeDB 0.92
InfoSys::FreeDB is a Perl module for FreeDB connection factory. more>>
InfoSys::FreeDB is a Perl module for FreeDB connection factory.
SYNOPSIS
require InfoSys::FreeDB;
require InfoSys::FreeDB::Entry;
# Read entry from the default CD device
my $entry = InfoSys::FreeDB::Entry->new_from_cdparanoia();
# Create a HTTP connection
my $fact = InfoSys::FreeDB->new();
my $conn = $fact->create_connection( {
client_name => testing-InfoSys::FreeDB,
client_version => $InfoSys::FreeDB::VERSION,
} );
# Query FreeDB
my $res_q = $conn->query( $entry );
scalar( $res_q->get_match() ) ||
die no matches found for the disck in the default CD-Rom drive;
# Read the first match
my $res_r = $conn->read( ( $res_q->get_match() )[0] );
# Write the entry to STDERR
use IO::Handle;
my $fh = IO::Handle->new_from_fd( fileno(STDERR), w );
$res_r->get_entry()->write_fh( $fh );
<<lessSYNOPSIS
require InfoSys::FreeDB;
require InfoSys::FreeDB::Entry;
# Read entry from the default CD device
my $entry = InfoSys::FreeDB::Entry->new_from_cdparanoia();
# Create a HTTP connection
my $fact = InfoSys::FreeDB->new();
my $conn = $fact->create_connection( {
client_name => testing-InfoSys::FreeDB,
client_version => $InfoSys::FreeDB::VERSION,
} );
# Query FreeDB
my $res_q = $conn->query( $entry );
scalar( $res_q->get_match() ) ||
die no matches found for the disck in the default CD-Rom drive;
# Read the first match
my $res_r = $conn->read( ( $res_q->get_match() )[0] );
# Write the entry to STDERR
use IO::Handle;
my $fh = IO::Handle->new_from_fd( fileno(STDERR), w );
$res_r->get_entry()->write_fh( $fh );
Download (0.060MB)
Added: 2007-03-07 License: Perl Artistic License Price:
965 downloads
Net::Chat::Daemon 0.3
Net::Chat::Daemon is a Perl module to run a daemon that is controlled via instant messaging. more>>
Net::Chat::Daemon is a Perl module to run a daemon that is controlled via instant messaging.
ABSTRACT
This package is intended to serve as a superclass for objects that want to communicate via IM messages within a distributed network of client nodes and a coordinator, without dealing with the complexities or implementation details of actually getting the messages from place to place.
It pretends to be protocol-neutral, but for now and the conceivable future will only work with a Jabber transport. (It directly uses the message objects and things that Jabber returns.)
Note that this package will NOT help you implement an instant messaging server. This package is for writing servers that communicate with other entities via instant messages -- servers written using this package are instant messaging *clients*.
SYNOPSIS
package My::Server;
use base Net::Chat::Daemon;
sub handleHello {
return "hello to you too";
}
sub handleSave {
my ($filename, $file) = @_;
return "denied" unless $filename =~ /^[.w]+$/;
open(my $fh, ">/var/repository/$filename") or return "failed: $!";
print $fh $file;
close $fh or return "failed: $!";
return "ok";
}
sub someMethod {
my ($self, @args) = @_;
.
.
.
}
sub new {
my ($class, $user, %options) = @_;
return $class->SUPER::new(%options,
commands => { callMethod => someMethod,
save => &handleSave });
}
package main;
my $server = My::Server->new(myuserid@jabber.org);
$server->process();
# or to do it all in one step, and retry connections for 5 minutes
# (300 seconds) before failing due to problems reaching the server:
My::Server->run(myuserid@jabber.org, retry => 300);
When you run this, you should be able to send a message to userid@jabber.org saying "hello" and get a response back, or "callMethod a b c" to call the method with the given arguments.
To use the "save" command, youll need to use a command-line client capable of sending attachments in the format expected by this server (it currently does not use any standard file-sending formats).
The jabber command packaged with this module can do this via the -a command-line option.
A note on the implementation: when I first wrote this, it was really only intended to be used with Jabber. The code hasnt been fully restructured to remove this assumption.
<<lessABSTRACT
This package is intended to serve as a superclass for objects that want to communicate via IM messages within a distributed network of client nodes and a coordinator, without dealing with the complexities or implementation details of actually getting the messages from place to place.
It pretends to be protocol-neutral, but for now and the conceivable future will only work with a Jabber transport. (It directly uses the message objects and things that Jabber returns.)
Note that this package will NOT help you implement an instant messaging server. This package is for writing servers that communicate with other entities via instant messages -- servers written using this package are instant messaging *clients*.
SYNOPSIS
package My::Server;
use base Net::Chat::Daemon;
sub handleHello {
return "hello to you too";
}
sub handleSave {
my ($filename, $file) = @_;
return "denied" unless $filename =~ /^[.w]+$/;
open(my $fh, ">/var/repository/$filename") or return "failed: $!";
print $fh $file;
close $fh or return "failed: $!";
return "ok";
}
sub someMethod {
my ($self, @args) = @_;
.
.
.
}
sub new {
my ($class, $user, %options) = @_;
return $class->SUPER::new(%options,
commands => { callMethod => someMethod,
save => &handleSave });
}
package main;
my $server = My::Server->new(myuserid@jabber.org);
$server->process();
# or to do it all in one step, and retry connections for 5 minutes
# (300 seconds) before failing due to problems reaching the server:
My::Server->run(myuserid@jabber.org, retry => 300);
When you run this, you should be able to send a message to userid@jabber.org saying "hello" and get a response back, or "callMethod a b c" to call the method with the given arguments.
To use the "save" command, youll need to use a command-line client capable of sending attachments in the format expected by this server (it currently does not use any standard file-sending formats).
The jabber command packaged with this module can do this via the -a command-line option.
A note on the implementation: when I first wrote this, it was really only intended to be used with Jabber. The code hasnt been fully restructured to remove this assumption.
Download (0.013MB)
Added: 2007-04-04 License: Perl Artistic License Price:
933 downloads
GD::Image::CopyIFS 0.25
GD::Image::CopyIFS is a Perl module for fractal-based image copying and resizing. more>>
GD::Image::CopyIFS is a Perl module for fractal-based image copying and resizing.
SYNOPSIS
# zoom in on an area of an image
use GD::Image::CopyIFS;
my $width = 64;
my $height = 60;
my $scale = 4;
my $neww = $scale * $width;
my $newh = $scale * $height;
my $src_file = src.jpeg;
my $src_img = GD::Image->newFromJpeg($src_file, 1);
my $dst_img = GD::Image->new($neww, $newh, 1);
my @opts = ($src_img, 0, 0, 110, 120,
$neww, $newh, $width, $height);
$dst_img->copyIFS(@opts);
my $dst_file = dst.jpeg;
open(my $fh, >, $dst_file) or die "Cannot open $dst_file: $!";
binmode $fh;
print $fh $im->jpeg;
close $fh;
# create a resized image scaled by a factor $scale
use GD::Image::CopyIFS;
my $src_file = src.jpeg;
my $src_img = GD::Image->newFromJpeg($src_file, 1);
my $scale = 2.45;
my $dst_img = GD::Image->thumbIFS($src_img, scale => $scale);
my $dst_file = dst.jpeg;
open(my $fh, >, $dst_file) or die "Cannot open $dst_file: $!";
binmode $fh;
print $fh $im->jpeg;
close $fh;
This module adds to the GD::Image module of GD two methods: copyIFS, used to copy and resize an area of one image onto another image, and thumbIFS, used to create a rescaled image from an original. The copyIFS method is used analagously to the copyResized or copyResampled methods of the GD module.
The algorithm employed uses what is known as a fractal interpolating function, which uses an Iterated Function System (IFS) to interpolate functions specified at discrete points. The basic procedure is to create an IFS based on the pixel colors of an image, and then from this construct a new IFS based on the parameters specified when rescaling an area of the image. A random iteration algorithm is then used to construct an image from this new IFS. For details, see http://ecommons.uwinnipeg.ca/archive/00000026/.
Note that this algorithm may give good results for images of natural objects, as there is generally a fractal nature present in most such shapes. It typically will not give good results for more geometric shapes, such as lettering.
<<lessSYNOPSIS
# zoom in on an area of an image
use GD::Image::CopyIFS;
my $width = 64;
my $height = 60;
my $scale = 4;
my $neww = $scale * $width;
my $newh = $scale * $height;
my $src_file = src.jpeg;
my $src_img = GD::Image->newFromJpeg($src_file, 1);
my $dst_img = GD::Image->new($neww, $newh, 1);
my @opts = ($src_img, 0, 0, 110, 120,
$neww, $newh, $width, $height);
$dst_img->copyIFS(@opts);
my $dst_file = dst.jpeg;
open(my $fh, >, $dst_file) or die "Cannot open $dst_file: $!";
binmode $fh;
print $fh $im->jpeg;
close $fh;
# create a resized image scaled by a factor $scale
use GD::Image::CopyIFS;
my $src_file = src.jpeg;
my $src_img = GD::Image->newFromJpeg($src_file, 1);
my $scale = 2.45;
my $dst_img = GD::Image->thumbIFS($src_img, scale => $scale);
my $dst_file = dst.jpeg;
open(my $fh, >, $dst_file) or die "Cannot open $dst_file: $!";
binmode $fh;
print $fh $im->jpeg;
close $fh;
This module adds to the GD::Image module of GD two methods: copyIFS, used to copy and resize an area of one image onto another image, and thumbIFS, used to create a rescaled image from an original. The copyIFS method is used analagously to the copyResized or copyResampled methods of the GD module.
The algorithm employed uses what is known as a fractal interpolating function, which uses an Iterated Function System (IFS) to interpolate functions specified at discrete points. The basic procedure is to create an IFS based on the pixel colors of an image, and then from this construct a new IFS based on the parameters specified when rescaling an area of the image. A random iteration algorithm is then used to construct an image from this new IFS. For details, see http://ecommons.uwinnipeg.ca/archive/00000026/.
Note that this algorithm may give good results for images of natural objects, as there is generally a fractal nature present in most such shapes. It typically will not give good results for more geometric shapes, such as lettering.
Download (0.021MB)
Added: 2007-04-24 License: Perl Artistic License Price:
913 downloads
Text::vFile::toXML 0.03
Text::vFile::toXML can convert vFiles into equivalent XML. more>>
Text::vFile::toXML can convert vFiles into equivalent XML.
SYNOPSIS
This module converts iCalendar (iCal : generically, vFile) files into their (equivalent) XML (xCalendar / xCal) representation, according to Royers IETF Draft (http://tools.ietf.org/html/draft-royer-calsch-xcal-03).
# Enable functional interface
use Text::vFile::toXML qw(to_xml);
# Input filename
my $arg = "input.file";
my $a = Text::vFile::toXML->new(filename => $arg)->to_xml;
my $b = Text::vFile::toXML->new(filehandle =>
do { open my $fh, $arg or die "cant open ics: $!"; $fh }
)->to_xml;
use Text::vFile::asData; # to make the functional example work
my $data =
Text::vFile::asData->new->parse(
do {
open my $fh, $arg
or die "Cant open vFile: $!"; $fh
}
);
my $c = Text::vFile::toXML->new(data => $data)->to_xml;
# Use functional interface
my $d = to_xml($data);
# Now ($a, $b, $c, $d) all contain the same XML string.
<<lessSYNOPSIS
This module converts iCalendar (iCal : generically, vFile) files into their (equivalent) XML (xCalendar / xCal) representation, according to Royers IETF Draft (http://tools.ietf.org/html/draft-royer-calsch-xcal-03).
# Enable functional interface
use Text::vFile::toXML qw(to_xml);
# Input filename
my $arg = "input.file";
my $a = Text::vFile::toXML->new(filename => $arg)->to_xml;
my $b = Text::vFile::toXML->new(filehandle =>
do { open my $fh, $arg or die "cant open ics: $!"; $fh }
)->to_xml;
use Text::vFile::asData; # to make the functional example work
my $data =
Text::vFile::asData->new->parse(
do {
open my $fh, $arg
or die "Cant open vFile: $!"; $fh
}
);
my $c = Text::vFile::toXML->new(data => $data)->to_xml;
# Use functional interface
my $d = to_xml($data);
# Now ($a, $b, $c, $d) all contain the same XML string.
Download (0.005MB)
Added: 2007-08-22 License: Perl Artistic License Price:
793 downloads
Convert::BinHex 1.119
Convert::BinHex can extract data from Macintosh BinHex files. more>>
Convert::BinHex can extract data from Macintosh BinHex files.
ALPHA WARNING: this code is currently in its Alpha release. Things may change drastically until the interface is hammered out: if you have suggestions or objections, please speak up now!
SYNOPSIS
Simple functions:
use Convert::BinHex qw(binhex_crc macbinary_crc);
# Compute HQX7-style CRC for data, pumping in old CRC if desired:
$crc = binhex_crc($data, $crc);
# Compute the MacBinary-II-style CRC for the data:
$crc = macbinary_crc($data, $crc);
Hex to bin, low-level interface. Conversion is actually done via an object ("Convert::BinHex::Hex2Bin") which keeps internal conversion state:
# Create and use a "translator" object:
my $H2B = Convert::BinHex->hex2bin; # get a converter object
while (< STDIN >) {
print $STDOUT $H2B->next($_); # convert some more input
}
print $STDOUT $H2B->done; # no more input: finish up
Hex to bin, OO interface. The following operations must be done in the order shown!
# Read data in piecemeal:
$HQX = Convert::BinHex->open(FH=>*STDIN) || die "open: $!";
$HQX->read_header; # read header info
@data = $HQX->read_data; # read in all the data
@rsrc = $HQX->read_resource; # read in all the resource
Bin to hex, low-level interface. Conversion is actually done via an object ("Convert::BinHex::Bin2Hex") which keeps internal conversion state:
# Create and use a "translator" object:
my $B2H = Convert::BinHex->bin2hex; # get a converter object
while (< STDIN >) {
print $STDOUT $B2H->next($_); # convert some more input
}
print $STDOUT $B2H->done; # no more input: finish up
Bin to hex, file interface. Yes, you can convert to BinHex as well as from it!
# Create new, empty object:
my $HQX = Convert::BinHex->new;
# Set header attributes:
$HQX->filename("logo.gif");
$HQX->type("GIFA");
$HQX->creator("CNVS");
# Give it the data and resource forks (either can be absent):
$HQX->data(Path => "/path/to/data"); # here, data is on disk
$HQX->resource(Data => $resourcefork); # here, resource is in core
# Output as a BinHex stream, complete with leading comment:
$HQX->encode(*STDOUT);
PLANNED!!!! Bin to hex, "CAP" interface. Thanks to Ken Lunde for suggesting this.
# Create new, empty object from CAP tree:
my $HQX = Convert::BinHex->from_cap("/path/to/root/file");
$HQX->encode(*STDOUT);
BinHex is a format used by Macintosh for transporting Mac files safely through electronic mail, as short-lined, 7-bit, semi-compressed data streams. Ths module provides a means of converting those data streams back into into binary data.
<<lessALPHA WARNING: this code is currently in its Alpha release. Things may change drastically until the interface is hammered out: if you have suggestions or objections, please speak up now!
SYNOPSIS
Simple functions:
use Convert::BinHex qw(binhex_crc macbinary_crc);
# Compute HQX7-style CRC for data, pumping in old CRC if desired:
$crc = binhex_crc($data, $crc);
# Compute the MacBinary-II-style CRC for the data:
$crc = macbinary_crc($data, $crc);
Hex to bin, low-level interface. Conversion is actually done via an object ("Convert::BinHex::Hex2Bin") which keeps internal conversion state:
# Create and use a "translator" object:
my $H2B = Convert::BinHex->hex2bin; # get a converter object
while (< STDIN >) {
print $STDOUT $H2B->next($_); # convert some more input
}
print $STDOUT $H2B->done; # no more input: finish up
Hex to bin, OO interface. The following operations must be done in the order shown!
# Read data in piecemeal:
$HQX = Convert::BinHex->open(FH=>*STDIN) || die "open: $!";
$HQX->read_header; # read header info
@data = $HQX->read_data; # read in all the data
@rsrc = $HQX->read_resource; # read in all the resource
Bin to hex, low-level interface. Conversion is actually done via an object ("Convert::BinHex::Bin2Hex") which keeps internal conversion state:
# Create and use a "translator" object:
my $B2H = Convert::BinHex->bin2hex; # get a converter object
while (< STDIN >) {
print $STDOUT $B2H->next($_); # convert some more input
}
print $STDOUT $B2H->done; # no more input: finish up
Bin to hex, file interface. Yes, you can convert to BinHex as well as from it!
# Create new, empty object:
my $HQX = Convert::BinHex->new;
# Set header attributes:
$HQX->filename("logo.gif");
$HQX->type("GIFA");
$HQX->creator("CNVS");
# Give it the data and resource forks (either can be absent):
$HQX->data(Path => "/path/to/data"); # here, data is on disk
$HQX->resource(Data => $resourcefork); # here, resource is in core
# Output as a BinHex stream, complete with leading comment:
$HQX->encode(*STDOUT);
PLANNED!!!! Bin to hex, "CAP" interface. Thanks to Ken Lunde for suggesting this.
# Create new, empty object from CAP tree:
my $HQX = Convert::BinHex->from_cap("/path/to/root/file");
$HQX->encode(*STDOUT);
BinHex is a format used by Macintosh for transporting Mac files safely through electronic mail, as short-lined, 7-bit, semi-compressed data streams. Ths module provides a means of converting those data streams back into into binary data.
Download (0.083MB)
Added: 2006-08-04 License: Perl Artistic License Price:
1234 downloads
Secleted [ 0 ] software to compare
Copyright Notice:
Software piracy is theft, Using crack, password, serial numbers, registration codes, key generators is illegal and prevent future software development. The above fh search only lists software in full, demo and trial versions for free download. Download links are directly from our mirror sites or publisher sites, torrent files or links from rapidshare.com, yousendit.com or megaupload.com are not allowed
Contact Us | Submit Software | Advertise with us | Terms and Conditions | Privacy Policy | Publisher List | Browse Categories | Blog | Discussion Board
Copyright (c)2005-2009 WareSeeker.com. All rights reserved.
Copyright (c)2005-2009 WareSeeker.com. All rights reserved.