Web Developer's Virtual Library: Encyclopedia of Web Design Tutorials, Articles and Discussions


WDVL Newsletter

Active Server Pages
JSP/Java Servlets
Microsoft SQL Server
Daily Backup
Dedicated Servers
Streaming Audio/Video
24-hour Support    

jobs.webdeveloper.com

Hiermenus


e-commerce
Partner With Us















Developer Channel
FlashKit.com
JavaScript.com
JavaScriptSource
Developer Jobs
ScriptSearch
StreamingMediaWorld
Web Developer's Journal
Web Developer's Virtual Library
WebDeveloper.com
Webreference
Web Hosts
XMLfiles.com

internet.com
IT
Developer
Internet News
Small Business
Personal Technology

Search internet.com
Advertise
Corporate Info
Newsletters
Tech Jobs
E-mail Offers


Handling Context: an Example - Page 22

July 27, 2001

Putting all the above together, here is a final version of list_files that handles both scalar, list, and void contexts, along with a sample program to test it out in each of the three contexts:

#!/usr/bin/perl
# listfile.pl
use warnings;
use strict;

sub list_files {
  die "Function called in void context" unless defined wantarray;
  my $path = shift;

  return wantarray?():undef unless defined $path;
  chomp $path;
  # remove trailing linefeed, if present
  $path.='/*' unless $path =~/\*/;
  # add wildcard if missing
  my @files = glob $path;
  return wantarray?@files:\@files;
}

print "Enter Path: ";
my $path = <>;

# call subroutine in list context
print "Get files as list:\n";
my @files = list_files($path);
foreach (sort @files) {
  print "\t$_\n";
}

# call subroutine in scalar context
print "Get files as scalar:\n";
my $files = list_files($path);
foreach (sort @{$files}) {
  print "\t$_  \n";
}

# to get a count we must now do so explicitly with $#...
# note that 'scalar would not work, it forces scalar context.
my $count = $#{list_files($path)}+1;
  print "Count: $count files\n";

# call subroutine void context - generates an error
list_files($path);

The name wantarray is something of a misnomer, since there is no such thing as 'array context'. A better name for it would have been wantlist.

Determining and Responding to the Calling Context - Page 21
Professional Perl Programming
Closures - Page 23


Up to => Home / Authoring / Languages / Perl / ProPerl




Jupiter Online Media: internet.comearthweb.comDevx.commediabistro.comGraphics.com

Search:

Jupitermedia Corporation has two divisions: Jupiterimages and Jupiter Online Media

Jupitermedia Corporate Info


Legal Notices, Licensing, & Permissions, Privacy Policy.

Web Hosting | Newsletters | Tech Jobs | Shopping | E-mail Offers