Helix Core is now P4. Product user interfaces will be updated soon. Learn more >>

P4 API for Perl Documentation | 2025.2

# Class P4

## Description

Main interface to the P4 Server client API.

This module provides an object-oriented interface to P4 Server, the Perforce version control system. Data is returned in Perl arrays and hashes and input can also be supplied in these formats.

Each `P4` object represents a connection to the P4 Server, also called P4 Server, and multiple commands may be executed (serially) over a single connection.

The basic model is to:

1. Instantiate your `P4` object.

2. Specify your P4 Server client environment.

   - `SetClient()`
   - `SetHost()`
   - `SetPassword()`
   - `SetPort()`
   - `SetUser()`

3. Connect to the Perforce service.

   The P4 Server protocol is not designed to support multiple concurrent queries over the same connection. Multithreaded applications that use the C++ API or derived APIs (including P4 API for Perl) should ensure that a separate connection is used for each thread, or that only one thread may use a shared connection at a time.

4. Run your P4 Server commands.
5. Disconnect from the Perforce service.

## Class methods

### P4::new() -> P4

Construct a new `P4` object. For example:

    my $p4 = new P4;

### P4::Identify() -> string

Print build information including P4 API for Perl version and P4 API for C/C++ version.

    print P4::Identify();

The constants `OS`, `PATCHLEVEL` and `VERSION` are also available to test an installation of P4 API for Perl without having to parse the output of `P4::Identify()`. Also reports the version of the OpenSSL library used for building the underlying P4 API for C/C++ with which P4 API for Perl was built.

### P4::ClearHandler() -> undef

Clear any configured output handler.

### P4::Connect() -> bool

Initializes the P4 Server client and connects to the server. Returns `false` on failure and `true` on success.

### P4::Disconnect() -> undef

Terminate the connection and clean up. Should be called before exiting.

### P4::ErrorCount() -> integer

Returns the number of errors encountered during execution of the last command.

### P4::Errors() -> list

Returns a list of the error strings received during execution of the last command.

### P4::Fetch<Spectype>( [name] ) -> hashref

Shorthand for running:

    $p4->Run( "<spectype>", "-o" );

and returning the first element of the result array. For example:

    $label      = $p4->FetchLabel( $labelname );
    $change     = $p4->FetchChange( $changeno );
    $clientspec = $p4->FetchClient( $clientname );

### P4::Format<Spectype>( hash ) -> string

Shorthand for running:

    $p4->FormatSpec( "<spectype>", hash);

and returning the results. For example:

    $change     = $p4->FetchChange();
    $change->{ 'Description' } = 'Some description';
    $form       = $p4->FormatChange( $change );
    printf( "Submitting this change:\n\n%s\n", $form );
    $p4->RunSubmit( $change );

### P4::FormatSpec( $spectype, $string ) -> string

Converts a P4 Server form of the specified type (`client`, `label`, etc.) held in the supplied hash into its string representation. Shortcut methods are available that obviate the need to supply the type argument. The following two examples are equivalent:

    my $client = $p4->FormatSpec( "client", $hash );

    my $client = $p4->FormatClient( $hash );

### P4::GetApiLevel() -> integer

Returns the current API compatibility level. Each iteration of the P4 Server is given a level number. As part of the initial communication, the client protocol level is passed between client application and the P4 Server. This value, defined in the P4 API for C/C++, determines the communication protocol level that the P4 Server client will understand. All subsequent responses from the P4 Server can be tailored to meet the requirements of that client protocol level.

For more information about the client protocol levels, see Protocol levels: server/client in the P4 Server Administration Documentation.

### P4::GetCharset() -> string

Return the name of the current charset in use. Applicable only when used withP4 Servers running in unicode mode.

### P4::GetClient() -> string

Returns the current P4 Server client name. This may have previously been set by `P4::SetClient()`, or may be taken from the environment or `P4CONFIG` file if any. If all that fails, it will be your hostname.

### P4::GetCwd() -> string

Returns the current working directory as your P4 Server client sees it.

### P4::GetEnv( $var ) -> string

Returns the value of a P4 Server environment variable, taking into account the settings of P4 Server variables in `P4CONFIG` files, and, on Windows or macOS, in the registry or user preferences.

### P4::GetHandler() -> Handler

Returns the output handler.

### P4::GetHost() -> string

Returns the client hostname. Defaults to your hostname, but can be overridden with `P4::SetHost()`

### P4::GetMaxLockTime( $value ) -> integer

Get the current `maxlocktime` setting.

### P4::GetMaxResults( $value ) -> integer

Get the current `maxresults` setting.

### P4::GetMaxScanRows( $value ) -> integer

Get the current `maxscanrows` setting.

### P4::GetPassword() -> string

Returns your P4 Server password. Taken from a previous call to `P4::SetPassword()` or extracted from the environment (`$ENV{P4PASSWD}`), or a `P4CONFIG` file.

### P4::GetPort() -> string

Returns the current address for your P4 Server server. Taken from a previous call to `P4::SetPort()`, or from `$ENV{P4PORT}` or a `P4CONFIG` file.

### P4::GetProg() -> string

Get the name of the program as reported to the P4 Server.

### P4::GetProgress() -> Progress

Returns the progress indicator.

### P4::GetTicketFile( [$string] ) -> string

Return the path of the current `P4TICKETS` file.

### P4::GetUser() -> String

Get the current user name. Taken from a previous call to `P4::SetUser()`, or from `$ENV{P4USER}` or a `P4CONFIG` file.

### P4::GetVersion( $string ) -> string

Get the version of your script, as reported to the P4 Server.

### P4::IsConnected() -> bool

Returns true if the session has been connected, and has not been dropped.

### P4::IsStreams() -> bool

Returns true if streams support is enabled on this server.

### P4::IsTagged() -> bool

Returns true if Tagged mode is enabled on this client.

### P4::IsTrack() -> bool

Returns true if server performance tracking is enabled for this connection.

### P4::Iterate<Spectype>(arguments) -> object

Iterate over spec results. Returns an iterable object with `next()` and `hasNext()` methods.

Valid <spectype>s are `clients`, `labels`, `branches`, `changes`, `streams`, `jobs`, `users`, `groups`, `depots` and `servers`. Valid arguments are any arguments that would be valid for the corresponding `P4::RunCmd()` command.

Arguments can be passed to the iterator to filter the results, for example, to iterate over only the first two client workspace specifications:

    $p4->IterateClients( "-m2" );

You can also pass the spec type as an argument:

    $p4->Iterate( "changes" );

For example, to iterate through client specs:

    use P4;

    my $p4 = P4->new;
    $p4->Connect or die "Couldn't connect";
    my $i = $p4->IterateClients();
    while($i->hasNext) {
      my $spec = $i->next;
      print( "Client: " . ($spec->{Client} or "<undef>") . "\n" );
    }

### P4::Messages() -> list

Returns an array of `P4::Message()` objects, one for each message (info, warning or error) sent by the server.

### P4::P4ConfigFile() -> string

Get the path to the current `P4CONFIG` file.

### P4::Parse<Spectype>( $string ) -> hashref

Shorthand for running:

    $p4-ParseSpec( "<spectype>", buffer);

and returning the results. For example:

    $p4 = new P4;
    $p4->Connect() or die( "Failed to connect to server" );
    $client = $p4->FetchClient();

    # Returns a string (equivalent to running 'p4 client -o' from the command-line)
    $client = $p4->FormatClient( $client );

    # Convert to a hashref
    $client = $p4->ParseClient( $client );
    # Convert back to string
    $client = $p4->FormatClient( $client );

Comments in forms are preserved. Comments are stored as a `comment` key in the spec hash and are accessible. For example:

    my $spec = $pc->ParseGroup( 'my_group' );
    print $spec->{'comment'};

### P4::ParseSpec( $spectype, $string ) -> hashref

Converts a P4 Server form of the specified type (client/label etc.) held in the supplied string into a hash and returns a reference to that hash. Shortcut methods are available to avoid the need to supply the type argument. The following two examples are equivalent:

    my $hash = $p4->ParseSpec( "client", $clientspec );

    my $hash = $p4->ParseClient( $clientspec );

Custom specifications require that you call `Fetch` first so that the `specDefs` can be determined by the API and later used by `ParseSpec`.

### P4::Run<Cmd>( [ $arg…​ ] ) -> list | arrayref

Shorthand for running:

    $p4-Run( "cmd", arg, ...);

and returning the results.

### P4::Run( "<cmd>", [ $arg…​ ] ) -> list | arrayref

Run a P4 Server command and return its results. Because P4 Server commands can partially succeed and partially fail, it is good practice to check for errors using `P4::ErrorCount()`.

Results are returned as follows:

- A list of results in array context
- An array reference in scalar context

The AutoLoader enables you to treat P4 Server commands as methods:

    p4->RunEdit( "filename.txt" );

is equivalent to:

    $p4->Run( "edit", "filename.txt" );

Note that the content of the array of results you get depends on (a) whether you’re using tagged mode, (b) the command you’ve executed, (c) the arguments you supplied, and (d) your P4 Server version.

Tagged mode and form parsing mode are turned on by default; each result element is a hashref, but this is dependent on the command you ran and your server version.

In non-tagged mode, each result element is a string. In this case, because the P4 Server sometimes asks the client to write a blank line between result elements, some of these result elements can be empty.

Note that the return values of individual P4 Server commands are not documented because they may vary between server releases.

To correlate the results returned by the P4 interface with those sent to the command line client, try running your command with RPC tracing enabled. For example:

Tagged mode: `p4 -Ztag -vrpc=1 describe -s 4321`

Non-Tagged mode: `p4 -vrpc=1 describe -s 4321`

Pay attention to the calls to `client-FstatInfo()`, `client-OutputText()`, `client-OutputData()` and `client-HandleError()`. Each call to one of these functions results in either a result element, or an error element.

### P4::RunFilelog( [$args …​], $fileSpec …​ ) -> list | arrayref

Runs a `p4 filelog` on the `fileSpec` provided and returns an array of `P4::DepotFile` objects when executed in tagged mode.

### P4::RunLogin(…​) -> list | arrayref

Runs `p4 login` using a password or ticket set by the user.

### P4::RunPassword( $oldpass, $newpass ) -> list | arrayref

A thin wrapper for changing your password from `$oldpass` to `$newpass`. Not to be confused with `P4::SetPassword()`.

### P4::RunResolve( [$resolver], [$args …​] ) -> string

Run a `p4 resolve` command. Interactive resolves require the `$resolver` parameter to be an object of a class derived from `P4::Resolver`. In these cases, the `P4::Resolve()` method of this class is called to handle the resolve. For example:

    $resolver = new MyResolver;
    $p4->RunResolve( $resolver );

To perform an automated merge that skips whenever conflicts are detected:

    use P4;

    package MyResolver;
    our @ISA = qw( P4::Resolver );

    sub Resolve( $ ) {
      my $self      = shift;
      my $mergeData = shift;

      # "s"kip if server-recommended hint is to "e"dit the file,
      # because such a recommendation implies the existence of a conflict
      return "s" if ( $mergeData->MergeHint() eq "e" );
      return $mergeData->MergeHint();
    }
    1;

    package main;

    $p4 = new P4;
    $resolver = new MyResolver;

    $p4->Connect() or die( "Failed to connect to Perforce" );
    $p4->RunResolve( $resolver, ... );

In non-interactive resolves, no `P4::Resolver` object is required. For example:

    $p4->RunResolve( "at" );

### P4::RunSubmit( $arg | $hashref, …​) -> list | arrayref

Submit a changelist to the server. To submit a changelist, set the fields of the changelist as required and supply any flags:

    $change = $p4->FetchChange();
    $change->{ 'Description' } = "Some description";
    $p4->RunSubmit( "-r", $change );

You can also submit a changelist by supplying the arguments as you would on the command line:

    $p4->RunSubmit( "-d", "Some description", "somedir/..." );

### P4::RunTickets() -> list

Get a list of tickets from the local tickets file. Each ticket is a hash object with fields for `Host`, `User`, and `Ticket`.

### P4::Save<Spectype>() -> list | arrayref

Shorthand for running:

    $p4->SetInput( $spectype );
    $p4->Run( "<spectype>", "-i");

For example:

    $p4->SaveLabel( $label );
    $p4->SaveChange( $changeno );
    $p4->SaveClient( $clientspec );

### P4::ServerCaseSensitive() -> integer

Returns an integer specifying whether or not the server is case-sensitive.

### P4::ServerLevel() -> integer

Returns an integer specifying the server protocol level. This is not the same as, but is closely aligned to, the server version. To find out your server’s protocol level, run `p4 -vrpc=5 info` and look for the `server2` protocol variable in the output.

For more information about the P4 Server version levels, see Protocol levels: server/client in the P4 Server Administration Documentation.

### P4::ServerUnicode() -> integer

Returns an integer specifying whether or not the server is in Unicode mode.

### P4::SetApiLevel( $integer ) -> undef

Specify the API compatibility level to use for this script. This is useful when you want your script to continue to work on newer server versions, even if the new server adds tagged output to previously unsupported commands.

The additional tagged output support can change the server’s output, and confound your scripts. Setting the API level to a specific value allows you to lock the output to an older format, thus increasing the compatibility of your script.

Must be called before calling `P4::Connect()`. For example:

    $p4->SetApiLevel( 67 ); # Lock to 2010.1 format
    $p4->Connect() or die( "Failed to connect to Perforce" );
    # etc.

### P4::SetCharset( $charset ) -> undef

Specify the character set to use for local files when used with aP4 Server running in unicode mode. Do not use unless yourP4 Serveris in unicode mode. Must be called before calling `P4::Connect()`. For example:

    $p4->SetCharset( "winansi" );
    $p4->SetCharset( "iso8859-1" );
    $p4->SetCharset( "utf8" );
    # etc.

### P4::SetClient( $client ) -> undef

Sets the name of your P4 Server client workspace. If you don’t call this method, then the client workspace name will default according to the normal P4 Server conventions:

1. Value from file specified by `P4CONFIG`
2. Value from `$ENV{P4CLIENT}`
3. Hostname

### P4::SetCwd( $path ) -> undef

Sets the current working directory for the client.

### P4::SetEnv( $var, $value ) -> undef

On Windows or macOS, set a variable in the registry or user preferences. To unset a variable, pass an empty string as the second argument. On other platforms, an exception is raised.

    $p4->SetEnv( "P4CLIENT", "my_workspace" );
    $P4->SetEnv( "P4CLIENT", "");

### P4::SetHandler( Handler ) -> Handler

Sets the output handler.

### P4::SetHost( $hostname ) -> undef

Sets the name of the client host, overriding the actual hostname. This is equivalent to `p4 -H hostname`, and only useful when you want to run commands as if you were on another machine.

### P4::SetInput( $string | $hashref | $arrayref ) -> undef

Save the supplied argument as input to be supplied to a subsequent command. The input may be a hashref, a scalar string, or an array of hashrefs or scalar strings. If you pass an array, the array will be shifted once each time the P4 Server command being executed asks for user input.

### P4::SetMaxLockTime( $integer ) -> undef

Limit the amount of time (in milliseconds) spent during data scans to prevent the server from locking tables for too long. Commands that take longer than the limit will be aborted. The limit remains in force until you disable it by setting it to zero. See `p4 help maxresults` for information on the commands that support this limit.

### P4::SetMaxResults( $integer ) -> undef

Limit the number of results for subsequent commands to the value specified. P4 Server will abort the command if continuing would produce more than this number of results. Once set, this limit remains in force unless you remove the restriction by setting it to a value of 0.

### P4::SetMaxScanRows( $integer ) -> undef

Limit the number of records P4 Server will scan when processing subsequent commands to the value specified. P4 Server will abort the command once this number of records has been scanned. Once set, this limit remains in force unless you remove the restriction by setting it to a value of 0.

### P4::SetPassword( $password ) -> undef

Specify the password to use when authenticating this user against the P4 Server - overrides all defaults. Not to be confused with `P4::Password()`.

### P4::SetPort( $port ) -> undef

Set the port on which your P4 Server is listening. Defaults to:

1. Value from file specified by `P4CONFIG`
2. Value from `$ENV{P4PORT}`
3. `perforce:1666`

### P4::SetProg( $program_name ) -> undef

Set the name of your script. This value is displayed in the server log on 2004.2 or later servers.

### P4::SetProgress( Progress ) -> Progress

Sets the progress indicator.

### P4::SetStreams( 0 | 1 ) -> undef

Enable or disable support for streams. By default, streams support is enabled at 2011.1 or higher (`P4::GetApiLevel()` >= 70). Streams support requires a server at 2011.1 or higher. You can enable or disable support for streams both before and after connecting to the server.

### P4::SetTicketFile( [$string] ) -> string

Set the path to the current `P4TICKETS` file (and return it).

### P4::SetTrack( 0 | 1 ) -> undef

Enable (1) or disable (0) server performance tracking for this connection. By default, performance tracking is disabled.

### P4::SetUser( $username ) -> undef

Set your P4 Server username. Defaults to:

1. Value from file specified by `P4CONFIG`
2. Value from `C<$ENV{P4USER}>`
3. OS username

### P4::SetVersion( $version ) -> undef

Specify the version of your script, as recorded in the P4 Server log file.

### P4::Tagged( 0 | 1 | $coderef ) -> undef

Enable (1) or disable (0) tagged output from the server, or temporarily toggle it.

By default, tagged output is enabled, but can be disabled (or re-enabled) by calling this method. If you provide a code reference, you can run a subroutine with the tagged status toggled for the duration of that reference. For example:

    my $GetChangeCounter = sub{ $p4->RunCounter('change')->[ 0 ] };
    my $changeno = $p4->Tagged( 0, $GetChangeCounter );

When running in tagged mode, responses from commands that support tagged output will be returned in the form of a hashref. When running in non-tagged mode, responses from commands are returned in the form of strings (that is, in plain text).

### P4::TrackOutput() -> list

If performance tracking is enabled with `P4::SetTrack()`, returns a list of strings corresponding to the performance tracking output of the most recently-executed command.

### P4::WarningCount() -> integer

Returns the number of warnings issued by the last command.

    $p4->WarningCount();

### P4::Warnings() -> list

Returns a list of warning strings from the last command

    $p4->Warnings();

Your search for returned results